1
#include <stdio.h>
main()
{
    int c ;
    while ((c = getchar()) != EOF)
    {
        int isEOF = (c==EOF);
        printf("is %c EOF: %d ", c, isEOF);
    }
}

Why printf() method is called twice on every input char here?

If i give a input 'a', I am getting the result like

E:\C_workouts>gcc CharIO.c -o CharIO.exe

E:\C_workouts>CharIO.exe
a
is a EOF: 0 is
 EOF: 0

The same happens on every input.

GOPI
  • 71
  • 2
  • 3
  • 8

3 Answers3

2

Because you typed 'a' and '\n'...

The '\n' is a result of pressing the [ENTER] key after typing into your terminal/console's input line. The getchar() function will return each character, one at a time, until the input buffer is clear. So your loop will continue to cycle until getchar() has eaten any remaining characters from the stdin stream buffer.

If you are expecting the stdin input buffer to be clear when calling getchar() then you should flush stdin with while((ch=getchar())!='\n'&&ch!=EOF); to consume any previous contents in the buffer just before calling getchar(). Some implementations (ie. many DOS/Windows compilers) offer a non-standard fflush(stdin);

Community
  • 1
  • 1
veganaiZe
  • 539
  • 5
  • 13
1

Because in some implementations of getchar() when you press the key 'x' and ENTER, there are two caracters in the buffer (the 'x' and a newline char). (I know, this is a little dumb) You should skip newlines in your loop.

Update: this was already answered here: Where does `getchar()` store the user input?

Community
  • 1
  • 1
leonbloy
  • 73,180
  • 20
  • 142
  • 190
  • It's subjective... but I don't think that the implementation behaves as one would expect, and tons of programmers (myself included) have been bitten by this. Judging from the man page ("reads the next character from stream") we would expect that each key is read as soon as it pressed; actually the stdin is buffered by lines. (which can besides be edited - i.e. a backspace wont be sent as a key, etc) http://c-faq.com/osdep/cbreak.html And even when one learns about this behaviour, is not obvious at all that the ENTER key will produce a newline character. – leonbloy Mar 31 '10 at 02:44
-2

This should work...

    int c ;
    while (((c=getchar())^EOF)) 
        printf("is %c EOF: %d ", c, c^EOF?0:1);
  • 1
    XOR with EOF is unnecessarily ugly. Also, your code still has the same behaviour as the OP's. – E.M. Mar 31 '10 at 20:46