PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 31, 2022

[FIXED] why use EOF to check if stdin buffer is cleared

 October 31, 2022     c, eof, stdin     No comments   

Issue

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?


Solution

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.



Answered By - John Bollinger
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing