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?
Yes, testing
c != EOF
makes a tremendous difference.getchar()
returnsEOF
in the event that it detects an error or end-of-file on the standard input. Both of those are entirely possible. Oncegetchar()
returnsEOF
, it is likely to returnEOF
again on every subsequent call, so the version that does not test forEOF
is at risk of going into an infinite loop.