为什么以下程序在C ++中提供不同的输出?

时间:2017-08-25 17:51:42

标签: c++ file-io

以下程序一次打印1 2 3 4 5。这意味着打印输出没有时间延迟。

#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;
}

但是这个节目打印

1

2

3

4

5

逐个表示我的输出时间延迟为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;
}

上述两个程序中究竟发生了什么?

注意:您无法看到在线编译器中两个输出的差异,因为它们会在程序终止后显示结果。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我能够获得所需的输出,一次出现一个元素,延迟时间为0.5秒。二手visual studio 2015。

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

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

答案 2 :(得分:-1)

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