[英]c++ stdout flushes stream unexpectedly
#include <iostream>
#include <thread>
using namespace std;
int main()
{
for (int i = 0; i < 10000; i++) {
cout << "Hello\n";
}
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
在我的代碼中,我沒有調用任何std::flush
或std::endl
,但是在 2 秒延遲之前打印了你好。 我期待在 2 秒延遲后打印所有的問候,但事實並非如此。 我的代碼運行如下:
Hello
Hello
.
.
.
Hello
Hello
(after 2 seconds)
2 seconds have passed
[terminated]
為什么會這樣?
首先,你寫的 output 比典型的文件緩沖區要多,所以你幾乎總是希望至少有一些output 在睡眠前出現。
其次,您正在執行許多單獨的 output 調用,因此如果cout
是單元緩沖的,則每個調用都會立即被刷新。
第三,您在每個項目的末尾寫一個新行,所以如果cout
是行緩沖的,(是的)每個項目都會立即被刷新。
因此,如果您希望在睡眠結束后更好地看到至少一些 output 出現,請關閉單元緩沖並去掉換行符:
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
int main()
{
cout << nounitbuf;
for (int i = 0; i < 1000; i++) {
cout << "Hello";
}
// display something different to make it easier for user to see
// whether all output showed up before sleep or not.
cout << "...";
this_thread::sleep_for(chrono::milliseconds(2000));
cout << "2 seconds have passed" << endl;
return 0;
}
但即使這樣,也不能保證行為會改變。 相反,大多數實現 go 都有些痛苦,以確保寫入控制台的 output 盡快顯示,因此即使您采取措施延遲它,它仍然可能會在睡眠前出現。 但這可能會稍微提高你的機會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.