在 C 中打印同一行并暂停
我想让我的程序打印一些东西,然后等待几秒钟,然后在同一行中打印其他东西。我尝试将其写为:
printf ("bla bla bla");
sleep (2);
printf ("yada yada yada\n");
但在输出中我需要等待 2 秒钟,然后我将整行打印为一个。当我尝试将输出放在不同的行中时,它确实打印时暂停了。
如何使其在同一行中暂停打印?
*在Linux上工作
I want to make my program to print something, then wait for a few seconds and then print something else in the same line. I've tried to write it as:
printf ("bla bla bla");
sleep (2);
printf ("yada yada yada\n");
but in the output I get to wait for 2 seconds and then I get the whole line printed as one. When I tried to put the output in different lines it did print with a pause.
How do I make it to print with a pause in the same line?
*Working on Linux
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
fflush 强制将 stdout 内部缓冲区刷新到屏幕。
fflush forces the stdout internal buffer to be flushed to the screen.
默认情况下,
stdout
是行缓冲流,这意味着您需要显式刷新它。它在换行符上隐式刷新。此行为是 C99 标准强制规定的。这意味着在您的第一个
printf
中,文本被添加到内部缓冲区中。这样做是为了提高效率,例如在打印大量小文本片段时。您的第二个 printf 包含换行符,这会导致流被刷新。如果需要,您可以通过 fflush(stdout); 显式刷新 stdout。
作为替代方案,您也可以使用无缓冲的 stderr,如
fprintf(stderr, "bla bla bla");
中所示,但顾名思义,它用于错误和警告。另请参阅SO问题 为什么 printf 在调用后不会刷新,除非格式字符串中有换行符?。
The
stdout
is a line buffered stream by default, this means you need to explicitly flush it. It is implicitly flushed on newline. This behavior is mandated by the C99 standard.This means in your first
printf
, the text is added to an internal buffer. This is done to improve efficiency, e.g. when printing lots of small text fragments.Your second
printf
contains a newline, and that causes the stream to get flushed. You can explicitly flushstdout
viafflush(stdout);
if you want.As an alternative you could also use the unbuffered stderr, as in
fprintf(stderr, "bla bla bla");
, but as its name implies it is intended for errors and warnings.See also the SO question Why does printf not flush after the call unless a newline is in the format string?.