c++ - 为什么 cout 立即输出?

标签 c++ io output buffer cout

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).

有关更多信息,请参阅 sync_with_stdio cppreference 上的功能引用页.

从那个页面,函数...

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.

关于c++ - 为什么 cout 立即输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47873267/

相关文章:

c++ - 奇怪的 std::nan 错误

c++ - 我的功能有什么问题

string - Haskell 中连接字符串和 IO 整数

c++ - Sublime Text 没有构建输出

python 根据二叉树检查值,空输出

c++ - 如何在 C++ 中检测 win32 进程的创建/终止

c++ - 将QCheckBox的状态保存在文件中,程序重启时加载状态

java - 如何在 JComponent 中显示 ArrayList 项

IOMeter iobw.tst 文件

r - 根据 CI 输出制作表格