为什么使用EOF检查是否清除了stdin缓冲区 [英] why use EOF to check if stdin buffer is cleared

查看:101
本文介绍了为什么使用EOF检查是否清除了stdin缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下...

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?

推荐答案


我想知道两者之间是否有任何区别????对EOF的测试有什么区别吗?

I am wondering if there is any difference between the 2??? Does testing for EOF make any difference?

是的,测试 c!= EOF 会有很大的不同。 getchar()在标准输入中检测到错误或文件结尾,则返回 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缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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