“printf"不会立即打印字符串 [英] "printf" doesn't print a string immediately

查看:96
本文介绍了“printf"不会立即打印字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么 printf 在调用后不会刷新,除非格式字符串中有换行符?(在 C 中)

我有这样的代码:

printf("Starting nets allocation...");
while(...)
{
    ...some operations...
}
puts("DONE");

代码应立即打印字符串Starting nets allocation...",然后在循环后应打印DONE".

The code should prints immediately the string "Starting nets allocation..." then, after the loop, should prints "DONE".

相反,程序首先执行循环,然后打印字符串Starting nets allocation...DONE"为什么会发生?我该如何解决?

Instead, the program performs first the loop and then prints the string "Starting nets allocation...DONE" why it happens? How can I resolve this?

推荐答案

输出流 stdout 默认是缓冲的,所以如果你想要立即输出,你需要刷新输出流 - 使用fflush - 或导致在 printf 中打印换行符:

The output stream stdout is buffered by default, so if you want immediate output you'll need to flush the output stream - using fflush - or cause a newline to be printed in the printf:

printf("Starting nets allocation...");
fflush(stdout);    

或者:

printf("Starting nets allocation...\n");

请注意,您还可以使用 stdio.h 中的 setbuf 函数在文件指针级别控制缓冲:

Note that you can also control buffering at a file pointer level using the setbuf function from stdio.h:

setbuf(stdout, NULL);

setbuf 的第二个参数是调用者提供的缓冲区,用于缓冲输出到流.传递 NULL 表示要禁用缓冲,相当于:

The second argument to setbuf is a buffer supplied by the caller to be used for buffering output to the stream. Passing NULL indicates that buffering is to be disabled, and is equivalent to:

setvbuf(stdout, NULL, _IONBF, 0);

这也会禁用指定流上的缓冲.

which also disables buffering on the specified stream.

查看 setbuf 的文档此处.

这篇关于“printf"不会立即打印字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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