开发者

Unexpected putchar output when reading integer input with getchar

I was going through this program:

#include<stdio.h>

main()
{
 int c;

 c = getchar();

 while(c != EOF) {
   putchar(c);
   c = getchar();
  }
}

Since the variable c is integer, it should store the integer equivalent value for the given input. Output shows 'a' is printed as 'a', 'b' a开发者_如何学JAVAs 'b' and 'c' as 'c' but, when I enterd the vale 65, output was also 65! So there must be some difference in the storage formats of the value 65 and the char 'a'

How are both values discriminated from each other?


It's because input 65 is being considered as two different character inputs, and the program is printing them sequentially.

When you entered 6, the program reads it instantly and checks that it's not EOF, so it's printing it to the console. Then when you entered 5, it's again taking it as an input. Since this is also not EOF, your program is again printing it.

So you are entering two characters, and this program is printing it correctly to the console, just as it supposed to do. Other than that, there is no discrimination. a's integer equivalent is 65, so it will print 65 if you print a character like this -

 char c = 'a';
 printf("%d", c);    // will print 65

and this will print a -

int i = 65;
printf("%c", i);    // will print a


Your code is executing exactly as written, however, the confusion lies with your understanding of the inputs given to the program.

When you typed 65 it was interpreted as two typed characters, namely '6' and '5'. As you noted, this is what was echo'd to the console each time putchar(c) was called in the while loop.


No, there is no difference in the storage of 65 and 'a'. Assigning either of these to a variable yield exactly the same result. The difference is only relevant to the input and output of the char. E.g. printf("%c", 65) yield an 'a', because that is part of the definition of printf(). The same is true for the other two functions that you mentioned, putchar() and getchar().

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜