如果我输入 abc
作为文本流,getchar()
会读取它并 putchar
打印它。我使用 printf 语句来跟踪到底发生了什么。但是在打印输入文本流的字符后,我得到了一个奇怪的输出。它再次进入 while
循环并执行这两个 printf
语句,即当 i
为 4
时。这是否将我的 Enter 键作为输入。如果"is",我也尝试使用 fflush ,但这又产生了另一个问题。在我 fflush
使用 getchar
创建问题后,没有打印任何字符。为什么会发生这种情况以及如何解决它?
如果我使用 fflush(stdin)
会发生什么
#include <stdio.h>
main(){
c=getchar();
fflush(stdin);
while(c!= EOF)
{
putchar(c);
c=getchar();
fflush(stdin);
}
}
使用fflush
时,我在控制台上写ABC
。它只是 getchar()
'a' 并打印它。它甚至没有得到剩余的字符。
下面是我在使用fflush
之前所说的主程序。
#include <stdio.h>
main()
{
int c,i=1;
c=getchar();
while(c!= EOF) // while(c=getchar!=EOF) putchar(c);
{
printf("\n\nthis is upper %d time in loop i.e. before the putchar\n\n",i);
putchar(c);
printf("\n\nthis is down %d time in loop i.e. after the putchar\n\n",i);
c=getchar();
i++;
}
}
最佳答案
#include <stdio.h>
int main(){
int c;
while((c=getchar())!=EOF && c != '\n'){
putchar(c);
}
return 0;
}
<小时/>
while((c=getchar())!=EOF){
if(c == '\n')
break;//exit this while-loop
putchar(c);
}
关于c - 为什么 getchar 和 putchar 会出现这种情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25735211/