为什么 cout 立即输出?

Why is cout outputting immediately?

cout 是缓冲流。这意味着数据将被写入缓冲区,并在流被刷新、程序终止或缓冲区完全填满时打印。

我做了一个小程序来测试它是如何工作的,但我不明白为什么它在满足上述任何条件之前就打印出来。

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    cout << "Test";
    float secs = 5;
    clock_t delay = secs * CLOCKS_PER_SEC;
    clock_t start = clock();
    while (clock() - start < delay) { }
    return 0;
}

当运行时,循环开始前输出"Test"

为什么我的输出直到程序终止才被缓冲?

here 上对此进行了很好的讨论。

来自其中一个答案:

Every C++ stream uses an associated stream buffer object to perform buffering.

When std::cout is constructed, it uses the stream buffer associated with the object stdout, declared in <cstdio>. By default, operations on std::cout can be freely mixed with <cstdio> output functions like std::printf().

In practical terms, synchronization usually means that a standard iostream object and a standard stdio object share a buffer. - IS

If std::ios_base::sync_with_stdio(false) is called (before any input or output operations on the standard streams), the standard C++ streams operate independently of the standard C streams (ie. they switch to their own separate stream buffers).

有关更多信息,请参阅 cppreference 上的 sync_with_stdio 函数参考页。

从该页面开始,函数...

Sets whether the standard C++ streams are synchronized to the standard C streams after each input/output operation.

...In practice, this means that the synchronized C++ streams are unbuffered, and each I/O operation on a C++ stream is immediately applied to the corresponding C stream's buffer. This makes it possible to freely mix C++ and C I/O.

但是,请注意在已经有读取或写入之后再调用此函数:

If this function is called after I/O has occurred on the standard stream, the behavior is implementation-defined: implementations range from no effect to destroying the read buffer.

还有一个很棒的对话here。这似乎与scohe001提到的一些事情有关,但是有点不同,所以我会把它放在它自己的答案中。

与上述答案相关的是该论坛上的 this post,它讨论了如何根据周围的其他代码刷新缓冲区。 Std::cout 函数与其他流函数以及 scohe001 提到的普通 c 库函数相关联。因此,如果调用了它所绑定的东西,它的缓冲区将在继续之前刷新。

您是在 Linux 上使用 gcc 编译它,还是在某些 windows 环境中使用 运行 编译它?上面那个论坛的 post here 讨论了 OS 特定的功能,windows 的 sleep() 可能会导致缓冲区被清除。否则正常的 gcc 编译的 c++ 代码将不会使用 sleep() 打印缓冲区,只要它没有遇到任何其他代码会在继续之前刷新缓冲区。

以上post信息量很大,这里就不复制粘贴了,请Whosebug大神见谅

希望这些信息对您有所帮助!