C语言 如何刷新控制台缓冲区?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4573457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to flush the console buffer?
提问by DoronS
i have some code that run repetedly :
我有一些重复运行的代码:
printf("do you want to continue? Y/N: \n");
keepplaying = getchar();
printf("要继续吗?是/否:\n");
保持播放 = getchar();
in the next my code is running it doesnt wait for input. i found out that getchar in the seconed time use '\n' as the charcter. im gussing this is due to some buffer the sdio has, so it save the last input which was "Y\n" or "N\n".
在接下来我的代码正在运行它不等待输入。我发现第二次 getchar 使用 '\n' 作为字符。我猜这是由于 sdio 有一些缓冲区,所以它保存了最后一个输入,即“Y\n”或“N\n”。
my Q is, how do i flush the buffer before using the getchar, which will make getchar wait for my answer?
我的问题是,如何在使用 getchar 之前刷新缓冲区,这将使 getchar 等待我的回答?
回答by Robert Groves
Flushing an input stream causes undefined behaviour.
刷新输入流会导致未定义的行为。
int fflush(FILE *ostream);
ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
int fflush(FILE *ostream);
ostream 指向一个输出流或一个更新流,其中没有输入最近的操作,fflush 函数会导致该流的任何未写入的数据被传递到主机环境以写入文件;否则,行为未定义。
To properly flush the input stream do something like the following:
要正确刷新输入流,请执行以下操作:
int main(void)
{
int ch;
char buf[BUFSIZ];
puts("Flushing input");
while ((ch = getchar()) != '\n' && ch != EOF);
printf ("Enter some text: ");
if (fgets(buf, sizeof(buf), stdin))
{
printf ("You entered: %s", buf);
}
return 0;
}
回答by Sudhakar Singh
use fflush() and flushall() before printf
在 printf 之前使用 fflush() 和 flushall()
回答by kevin.bui
As far as I know, flushallis not POSIX. In order to flush a console buffer in a standard way, you can simply use the command:
据我所知,flushall不是POSIX。为了以标准方式刷新控制台缓冲区,您只需使用以下命令:
fflush(NULL);
This topic seems to be a bit old but I hope this can still help the others.
这个话题似乎有点老了,但我希望这仍然可以帮助其他人。

