带 cout 的无缓冲输出

发布于 2024-08-03 18:48:42 字数 324 浏览 1 评论 0原文

如何从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

衣神在巴黎 2024-08-10 18:48:42

您可以设置 std::ios_base::unitbuf< /a> flag 在每次输出操作后通过调用 std::ios_base::setf

std::cout.setf(std::ios::unitbuf);

或使用std::unitbuf 操纵器

std::cout << std::unitbuf;

You can set the std::ios_base::unitbuf flag to flush output after each output operation either by calling std::ios_base::setf:

std::cout.setf(std::ios::unitbuf);

or using the std::unitbuf manipulator:

std::cout << std::unitbuf;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文