问题描述
说我有以下...
int main () {
char name [5] = "";
char c;
printf("Enter a name: ");
fgets(name,5,stdin);
while ((c = getchar()) != '\n');
printf("Exiting...);
getchar();
return 0;
}
while循环将清理标准输入缓冲区,但我也看到了循环也是如此...
The while loop will clean the stdin buffer but I have seen the loop done like this as well...
while ((c = getchar()) != '\n' && c != EOF);
我想知道两者之间是否有任何区别????对EOF的测试有什么区别吗?
I am wondering if there is any difference between the 2??? Does testing for EOF make any difference?
推荐答案
是的,测试 c!= EOF
会有很大的不同。 getchar()$ c如果$ c>在标准输入中检测到错误或文件结尾,则返回
返回 EOF
,这完全有可能。 > getchar() EOF
,很可能在以后的每个查询中再次返回 EOF
调用,因此该版本没有测试 EOF
会陷入无限循环的风险。
Yes, testing c != EOF
makes a tremendous difference. getchar()
returns EOF
in the event that it detects an error or end-of-file on the standard input. Both of those are entirely possible. Once getchar()
returns EOF
, it is likely to return EOF
again on every subsequent call, so the version that does not test for EOF
is at risk of going into an infinite loop.
这篇关于为什么使用EOF检查是否清除了stdin缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!