tags:

views:

278

answers:

2
#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.

+3  A: 

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: http://stackoverflow.com/questions/1004314/getchar-question

leonbloy
Thank you for the answer!
GOPI
Why is this "a little dumb"?
Roger Pate
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.htmlAnd even when one learns about this behaviour, is not obvious at all that the ENTER key will produce a newline character.
leonbloy
+1  A: 

This should work...

    int c ;
    while (((c=getchar())^EOF)) 
        printf("is %c EOF: %d ", c, c^EOF?0:1);
XOR with EOF is unnecessarily ugly. Also, your code still has the same behaviour as the OP's.
Whisty