开发者

'Enter' as an input?

Here is my c开发者_Python百科ode!(sorry for my poor english)

#include<stdio.h>

int convert(char ch);

int main(void)
{
     char ch=0;

     while(ch != 'q')
     {
         ch=getchar();
         ch=convert(ch);
         if(ch == -1)
            printf("wrong input");
         else 
            putchar(ch);
            putchar('\n');
     }

     return 0;
}

int convert(char ch)
{
    if(ch>='A' && ch<='Z')
        ch+=32;
    else if(ch>='a' && ch<='z')
        ch-=32;
    else
        return -1;
}

And this code is for changing A to a, z to Z convert small to capital lettor, or reverse.

but when done, i found something wierd cuz whenever i put a char to the program,

it always return both the result that i expected and another "wrong input". and i didnt put anything to my standard input except a charactor and a Enter.

So, here is my question.

The function getchar() or some other like fgetc, fgets recieve a 'enter' as a charactor?


The function getchar() or some other like fgetc, fgets recieve a 'enter' as a charactor?

Yes, 'Enter' is character 10. You can see this by adding one extra line:

ch=getchar();
printf("Received: %d\n", ch);
ch=convert(ch);

abc Received: 97

Received: 98

Received: 99

Received: 10


Here's some example code to help you understand getchar more.

Also, I think you need to put your else clause in brackets.

Change this:

else 
    putchar(ch);
    putchar('\n');

to this:

else
{
    putchar(ch);
    putchar('\n');
}

In C/C++, only the first line of code will be executed in an if/else block, unless you put { and } brackets around it to indicate that several lines should be considered as a single block.


Yes, it will. The newline is part of the line, so it will count as part of the input.

You might want to use newline as the character to quit the program, unless you need to handle multiple lines.

Edit: You might also want to use a do{}while loop instead of a traditional while loop


Yes, getchar() receives the 'enter' as well as any other character you type.

You can test for 'enter' with

if (ch == '\n') { /* ... */ }

Also, note that the characters other than the 'enter' are only received after you type the 'enter'. If you type 'q' and wait 5 minutes, the program will idle for those 5 minutes and only terminate after you press 'enter'.

That's the design behind "line buffered" input.


I suppose this question has been answered already, but it seems to me that convert has a problem that nobody has mentioned. The character is passed by value, so adding or subtracting 32 has no effect on ch. Furthermore, the only value explicitly returned by convert is -1. I don't see how this code can work as intended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜