在 while 循环中使用 getchar() [英] 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);
}
}
为什么这里的每个输入字符都会调用 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.
推荐答案
因为你输入了'a
' 和 '
'...
'
' 是在终端/控制台的输入行中输入后按 [ENTER]
键的结果.getchar()
函数将返回每个字符,一次一个,直到输入缓冲区清空.因此,您的循环将继续循环,直到 getchar()
吃掉 stdin
流缓冲区中的所有剩余字符.
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.
如果您希望在调用 getchar()
时清除 stdin
输入缓冲区,那么您应该刷新 stdin
使用 while((ch=getchar())!='
'&&ch!=EOF);
使用缓冲区中的任何先前内容就在调用 getchar()
之前.一些实现(即许多 DOS/Windows 编译器)提供了一个非标准的 fflush(stdin);
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);
这篇关于在 while 循环中使用 getchar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!