会在C++中堵塞和cout在输出值方面的行为有所不同?

发布于 2025-01-18 14:54:03 字数 426 浏览 5 评论 0原文

我期望Cout和Clog具有类似的行为,因为这两个都是缓冲输出。但是当我尝试时,它会出现不同。

COUT:

int main()
{
    cout<<"Hello World" ;
    while(1);
    return 0;
}

输出:没有 - &GT;由于COUT不是冲洗堵塞

int main()
{
    clog<<"Hello World" ;
    while(1);
    return 0;
}

输出:Hello World

问题:Cout和Clog都被缓冲,所以为什么输出不相同。如何打印“ Hello World”而不会冲洗缓冲区

I am expecting a similar behavior for Cout and Clog since both are buffered outputs. But when i am trying, it comes out different.

COUT:

int main()
{
    cout<<"Hello World" ;
    while(1);
    return 0;
}

Output: Nothing --> Since Cout is not flushed

CLOG:

int main()
{
    clog<<"Hello World" ;
    while(1);
    return 0;
}

Output: Hello World

Question: Both COUT and CLOG are buffered, so why not the output is same. How is "Hello World" being printed without the buffer being flushed

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

后知后觉 2025-01-25 14:54:03

首先,我不明白无限循环的目的。如果您尝试让线程进入睡眠状态,请查看这篇文章 StackOverflow 中有关 cpp 中线程睡眠的帖子

其次,如果您想刷新流,请使用 std::cout << std::flush;。

至于它们之间的区别:基本上 clog 是一个很少使用的输出流,类似于 cerr。基本上阻塞输出到 stderr,类似于 cerr,而不是 stdout。检查这些可能有助于您理解差异:COUT vs CERR vs CLOG
教程点

现在讨论 stdout 和 stderr 之间的区别。 Stdout 始终被缓冲,并在方便的时候或明确请求时自动刷新,同时 stderr 没有完全缓冲,并且总是立即打印内容,而不需要显式刷新。

First of all, I don't understand the purpose of the infinite loop. If you are trying to put the thread to sleep check this post StackOverflow post about thread sleeping in cpp,

Secondly, if you want to flush the stream use std::cout << std::flush;.

As for the difference between those: basically clog is a rarely used output stream similar to cerr. Basically clog outputs to stderr, similar to cerr, and not stdout. Checking these might help you understand the difference: COUT vs CERR vs CLOG,
Tutorialspoint.

Now onto the difference between stdout and stderr. Stdout is always buffered and is flushed automatically at a convenient time or when requested explicitly to do so, meanwhile stderr is not fully buffered and always prints stuff immediately, without needing to be flushed explicitly.

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