如何在 fgets 循环中正确刷新 stdin [英] How to properly flush stdin in fgets loop
问题描述
我在此处多次找到使用 while((c = getchar()) != '\n' && c != EOF)
清除 stdin 的示例,并且试图在通过 fgets 获取输入的循环中使用它.我需要刷新,因为循环从最后一个输入中获取 \n 字符并再次运行.
I have found the example of clearing stdin using while((c = getchar()) != '\n' && c != EOF)
on here a few times, and tried to use it in a loop that gets input via fgets. I need to flush, since the loop takes the \n character from the last input and runs with it again.
所以现在我必须按两次回车键.为什么会发生这种情况,我该如何解决?
So what happens is that I have to press enter twice now. Why is this happening, and how can I fix this?
#define BUFFER_LIMIT 50
do
{
int c;
while ((c = getchar()) != '\n' && c != EOF);
printf("console> ");
fgets(input_buffer, BUFFER_LIMIT-1, stdin);
if(do_something(input_buffer))
break;
} while(strncmp(input_buffer, "quit", 4) != 0);
推荐答案
所以现在我必须按两次回车键.为什么会发生这种情况,我该如何解决?
So what happens is that I have to press enter twice now. Why is this happening, and how can I fix this?
好吧,这就是您的代码所做的 - 它首先逐个字符读取,直到找到换行符.然后它调用 fgets()
这将......好吧,阅读直到它找到一个换行符(可能是逐个字符,但也可能以其他方式).
Well, that is what your code is doing - it first reads char-by-char until it finds newline. Then it calls fgets()
which will... well, read until it finds a newline (probably char-by-char, but, also possibly in some other way).
您可以尝试 fflush(stdin)
,但这并不能保证做您想要的(它只保证输出缓冲区,不保证输入).
You could try fflush(stdin)
, but that is not guaranteed to do what you want (it only gives guarantees for output buffers, not for input).
此外,您可以尝试 setbuf(stdin, NULL)
,它应该禁用标准输入的缓冲,因此没有任何东西可以刷新.我在不同的系统上尝试了几次,它奏效了,但此功能的文档对此并不是 100% 清楚.
Also, you may try setbuf(stdin, NULL)
which should disable buffering on standard input, so there would be nothing to flush. I tried this a few times on different systems and it worked, but documentation for this function is not 100% clear on this.
这篇关于如何在 fgets 循环中正确刷新 stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!