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?

2
  • simply as enter is a character input... Commented Aug 24, 2018 at 11:34
  • How many keys did you press, one or two? Commented Aug 24, 2018 at 11:50

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.