在while循环中使用getchar()

时间:2010-03-31 00:47:39

标签: c while-loop getchar

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

为什么在这里对每个输入字符串调用printf()方法两次?

如果我输入'a',我得到的结果就像

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

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

每次输入都会发生同样的情况。

3 个答案:

答案 0 :(得分:2)

因为您键入了&#39; a&#39; &#39; \n&#39; ...

&#39; \n&#39;键入到终端/控制台的输入行后按[ENTER]键的结果。 getchar()函数将一次返回一个字符,直到输入缓冲区清除为止。所以你的循环将继续循环,直到getchar()吃掉stdin流缓冲区中的任何剩余字符。

如果您希望在调用stdin时明确getchar()输入缓冲区,则应 刷新stdin { {1}}在调用while((ch=getchar())!='\n'&&ch!=EOF);之前使用缓冲区中的任何先前内容。某些实现(即许多DOS / Windows编译器)提供非标准getchar()

答案 1 :(得分:1)

因为在按下'x'和ENTER键时getchar()的某些实现中,缓冲区中有两个字符('x'和换行符char)。 (我知道,这有点愚蠢) 您应该在循环中跳过换行符。

更新:此处已经回答:Where does `getchar()` store the user input?

答案 2 :(得分:-1)

这应该有用......

    int c ;
    while (((c=getchar())^EOF)) 
        printf("is %c EOF: %d ", c, c^EOF?0:1);