Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

c - Using getchar() in a while loop

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because you typed 'a' and ' '...

The ' ' 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())!=' '&&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);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...