why use EOF to check if stdin buffer is cleared

感情迁移 提交于 2019-12-12 22:18:17

问题


Say I have the following...

int main () {     
   char name [5] = "";
   char c;
   printf("Enter a name: ");
   fgets(name,5,stdin);
   while ((c = getchar()) != '\n');
   printf("Exiting...);
   getchar();
   return 0;
}

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);

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/39667485/why-use-eof-to-check-if-stdin-buffer-is-cleared

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