循环中的fgetc(stdin)产生奇怪的行为 [英] fgetc(stdin) in a loop is producing strange behaviour

查看:203
本文介绍了循环中的fgetc(stdin)产生奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

while(1){
    printf("hello world !\n");
    fgetc(stdin);
}

运行时,我输入如下字母:

when this runs and I enter a letter like this:

hello world !
a

它将在下一个循环中忽略fgetc(stdin),并两次打印问候世界,而无需等待输入.

it ignores the fgetc(stdin) in the next loop and prints hello world twice without waiting for input.

hello world !
a
hello world !
hello world !
a
hello world !
hello world !
a
hello world !
hello world !
a
hello world !
hello world !

我尝试将fflush(stdin)放在fgetc(stdin)之前或之后,但是它仍然产生相同的行为,我在做什么错了?

I have tried putting fflush(stdin) before or after the fgetc(stdin) but it still produces the same behaviour, what am I doing wrong ?

推荐答案

终端倾向于行缓冲,这意味着可以逐行访问流内容.

Terminals tend to be line-buffered, meaning that stream contents are accessible on a line-by-line basis.

因此,当fgetc开始从STDIN读取时,它正在读取整行,其中包括以该行结尾的换行符.那是您正在阅读的第二个字符.

So, when fgetc starts reading from STDIN, it's reading a full line, which includes the newline character that ended that line. That's the second character you're reading.

对于fflush,它用于刷新输出缓冲区,而不是输入缓冲区.

As for fflush, that's for flushing output buffers, not input buffers.

因此,您要在此处执行的操作是通过清除输入缓冲区直到其为空来清除它,或者只是显式地忽略换行符.

So, what you want to do here is to purge the input buffer by reading from it until its empty, or just explicitly ignore newline characters.

这篇关于循环中的fgetc(stdin)产生奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆