Input buffer flush

2019-07-09 20:33发布

Consider the code below:

#include<stdio.h>
int main(){
char c;
while( ( c=getchar() ) != EOF )
        printf("%c\n",c);
return 0; 
}

I gave the input as: hi^Z

The output was:

h
i
(an arrow pointing towards left) 

[Sorry, I couldn't find character for the above arrow. ]

Can someone please explain the output ? Since ^Z is part of the character string and there are characters to flush, I think ^Z shouldn't have been passed and thus the output should be,

h
i
(new line )

P.S - I am on windows and ^Z thus is EOF.

标签: c eof getchar
2条回答
时光不老,我们不散
2楼-- · 2019-07-09 21:02

Refer http://www.cplusplus.com/reference/cstdio/getchar/ It says that return type of getchar is int. Compiler should have given warning. Please do not ignore such warnings.

You are assigning int to char which will result in loss. Try to get it into int and print it.

You can print int too in printf using %c and typecasting to char.

查看更多
何必那么认真
3楼-- · 2019-07-09 21:10

The problem here is, a char is not sufficient to hold a value of EOF. You need to make use of an int type.

Change the char c; to int c;.

That said, the getchar() will return any pending items in the standard input. If you use the key combo after some input, the action would be similar as flushing the stream. To get the EOF returned from getchar(), you need to press the key combination one more time.

In short, if you expect getchar() to return EOF on CTRL+Z make sure there's nothing in stdin.

That said, for a hosted environment, the proper signature of main() is int main(void), at least.

查看更多
登录 后发表回答