带 cout 的无缓冲输出
如何从 cout 获得无缓冲的输出,以便它立即写入控制台而不需要刷新(类似于 cerr)?
我以为可以通过 rdbuf()->pubsetbuf 来完成,但这似乎不起作用。下面的代码片段应该立即输出到控制台,然后等待几秒钟。但相反,它只是等待,并且仅在程序退出且缓冲区被刷新时输出。
#include <iostream>
int main()
{
std::cout.rdbuf()->pubsetbuf(0, 0);
std::cout << "A";
sleep(5);
}
How can you get unbuffered output from cout, so that it instantly writes to the console without the need to flush (similar to cerr)?
I thought it could be done through rdbuf()->pubsetbuf, but this doesn't seem to work. The following code snippet below is supposed to immediately output to the console, and then wait a few seconds. But instead, it just waits, and only outputs when the program exits and the buffer is flushed.
#include <iostream>
int main()
{
std::cout.rdbuf()->pubsetbuf(0, 0);
std::cout << "A";
sleep(5);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以设置
std::ios_base::unitbuf
< /a> flag 在每次输出操作后通过调用std::ios_base::setf
:或使用
std::unitbuf
操纵器:You can set the
std::ios_base::unitbuf
flag to flush output after each output operation either by callingstd::ios_base::setf
:or using the
std::unitbuf
manipulator: