在 while 循环中使用 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
每个输入都会发生同样的情况。
#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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您输入了“
a
”和“\n
”...“
\n
”是一个结果在终端/控制台的输入行中输入内容后按[ENTER]
键。getchar()
函数将一次返回每个字符,直到输入缓冲区清空为止。因此,您的循环将继续循环,直到 getchar() 吃掉 stdin 流缓冲区中的所有剩余字符。如果您希望在调用
getchar()
时清除stdin
输入缓冲区,那么您应该刷新stdin
与while((ch=getchar())!='\n'&&ch!=EOF);
在调用之前消耗缓冲区中的任何先前内容getchar()
。一些实现(即许多 DOS/Windows 编译器)提供非标准fflush(stdin);
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. Thegetchar()
function will return each character, one at a time, until the input buffer is clear. So your loop will continue to cycle untilgetchar()
has eaten any remaining characters from thestdin
stream buffer.If you are expecting the
stdin
input buffer to be clear when callinggetchar()
then you should flushstdin
withwhile((ch=getchar())!='\n'&&ch!=EOF);
to consume any previous contents in the buffer just before callinggetchar()
. Some implementations (ie. many DOS/Windows compilers) offer a non-standardfflush(stdin);
因为在 getchar() 的某些实现中,当您按“x”键和 ENTER 时,缓冲区中有两个字符(“x”和换行符)。 (我知道,这有点愚蠢)
您应该在循环中跳过换行符。
更新:这里已经回答了这个问题:`getchar()`在哪里存储用户输入?
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?
这应该有效...
This should work...