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 objectstdout
, declared in<cstdio>
. By default, operations onstd::cout
can be freely mixed with<cstdio>
output functions likestd::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/