Very simple program as an example.
#include <stdio.h>
void main()
{
int c; // has to be int so it's large enough to hold EOF
printf("Please press EOF (C^D in Linux)\n");
while ((c = getchar()) != EOF)
printf("That's not EOF! Try again.\n"); // why is this printed twice?
printf("EOF is ");
putchar(c);
printf(".\n");
}
The question is simple as well: why is line 8 executed twice? Shouldn't it work like this:
- Get input from the user and assign the value to variable
c
. - Check if
c
isn'tEOF
. - If it isn't, print That's not EOF! Try again. Go to step 1.
- If it is, print EOF is [whatever EOF is]..
- Terminate the program.
Instead of that, the step 3 is:
- If it isn't, print That's not EOF! Try again. twice. Go to step 1.
Confusing problem. Will someone explain to me why is this happening and how to fix it?