输入缓冲区刷新 [英] Input buffer flush

查看:96
本文介绍了输入缓冲区刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

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

我输入的内容为:hi ^ Z

I gave the input as: hi^Z

输出为:


h
i
(an arrow pointing towards left) 


[抱歉,我找不到上述箭头的字符。 ]

有人可以解释一下输出结果吗?因为^ Z是字符串的一部分,并且有要刷新的字符,所以我认为^ Z不应该被传递,因此输出应该是

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 )


PS-我在Windows上,^ Z因此是EOF。

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

推荐答案

这里的问题是 char 不足以容纳 EOF 的值。您需要使用 int 类型。

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

更改 char c; int c;

也就是说, getchar ()将在标准输入中返回任何个待处理项目。如果在某些输入后使用组合键,则该操作将类似于 flushing 流。要获取 getchar()返回的 EOF ,您需要再按一次组合键。

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.

简而言之,如果您期望 getchar()返回 EOF CTRL + Z 上,确保 stdin 中没有任何内容。

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

也就是说,对于托管环境, main()的正确签名是 int main(void) ,至少。

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

这篇关于输入缓冲区刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆