0

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:

  1. Get input from the user and assign the value to variable c.
  2. Check if c isn't EOF.
  3. If it isn't, print That's not EOF! Try again. Go to step 1.
  4. If it is, print EOF is [whatever EOF is]..
  5. Terminate the program.

Instead of that, the step 3 is:

  1. 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?

Hanlon
  • 432
  • 4
  • 13

0 Answers0