Input buffer flush

大兔子大兔子 提交于 2019-12-11 02:33:44

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/41136213/input-buffer-flush

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!