问题描述
#include <stdio.h>
main()
{
int c ;
while ((c = getchar()) != EOF)
{
int isEOF = (c==EOF);
printf("is %c EOF: %d ", c, isEOF);
}
}
为什么printf()的方法在这里的每一个字符输入两次调用?
Why printf() method is called twice on every input char here?
如果我给一个输入'A',我得到的结果类似。
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.
推荐答案
由于在getchar函数的一些实现()当您preSS的关键X,并回车,出现在缓冲区2 caracters(的'X 和换行字符)。 (我知道,这是一个有点哑)
你应该在你的循环跳过换行符。
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.
更新:这是已经在这里回答:http://stackoverflow.com/questions/1004314/getchar-question
Update: this was already answered here: http://stackoverflow.com/questions/1004314/getchar-question
这篇关于在循环使用的getchar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!