为什么下面的程序在C++中给出不同的输出?

问题描述:

以下程序一次打印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; 
} 

在上述两个程序中的字面意思是什么?

注意:在线编译器的输出结果不同,因为它们显示程序终止后的结果。

+0

“以下程序一次打印1 2 3 4 5',似乎不太可能,您是否发布了正确的代码? – George

+1

@SchwiftySzechuan它可以如果输出缓冲。 AFAIK'std :: endl'强制刷新,所以如果OP用' Borgleader

+0

OP两个样本都是相同的...... – Borgleader

“\ n”使输出转到下一行。它是换行符

+1

这不是问题的主题。 – KjMag

+0

是的..问题被编辑,造成了混乱 –

输出可能是行缓冲的,在这种情况下只有完整的行被发送到底层输出设备。

我能够得到所需的输出,每次有一个元素出现时间为0.5秒。使用visual studio 2015.

我建议你避免在线编译器。

它们通常在文本框中输出一次完整的输出。