以下程序一次打印1 2 3 4 5
。這意味着打印輸出沒有時間延遲。爲什麼下面的程序在C++中給出不同的輸出?
#include<iostream>
#include<stdio.h>
#include <thread>
using namespace std;
int main()
{
for(int i = 1; i <= 5; ++i)
{
cout << i << " ";
// Function to sleep the thread
this_thread::sleep_for(500ms);
}
return 0;
}
但這程序打印
逐個即我我得到0.5秒延時輸出。
#include<iostream>
#include<stdio.h>
#include <thread>
using namespace std;
int main()
{
for(int i = 1; i <= 5; ++i)
{
cout << i << "\n";
// Function to sleep thread
// for 0.5 sec
this_thread::sleep_for(500ms);
}
return 0;
}
在上述兩個程序中的字面意思是什麼?
注意:在線編譯器的輸出結果不同,因爲它們顯示程序終止後的結果。
「以下程序一次打印1 2 3 4 5',似乎不太可能,您是否發佈了正確的代碼? – George
@SchwiftySzechuan它可以如果輸出緩衝。 AFAIK'std :: endl'強制刷新,所以如果OP用'<< std :: endl'替換'\ n',它不應該一次全部出來。 – Borgleader
OP兩個樣本都是相同的...... – Borgleader