1

My code look like below

int i=0;
while(i<10){
cout<<"Hello";
sleep(1);
i++
}

In Windows the code prints on each loop but in Linux it prints everything after exiting while loop . And also if I put an endl at the last of cout then it prints on each loop. Why this happening ?. Can anyone explain this behavior?.

Haris
  • 13,645
  • 12
  • 90
  • 121

3 Answers3

4

Try to use cout.flush(); maybe the two OS has different policy in term of buffering the stdout.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
1

For efficiency reasons, sometimes the standard streams will be implemented with a buffer. Making lots of tiny writes can be slow, so it will store up your writes until it gets a certain amount of data before writing it all out at once.

Endl forces it to write out the current buffer, so you'll see the output immediately.

Antimony
  • 37,781
  • 10
  • 100
  • 107
0
#include <iostream>
using namespace std;

int main()
{
    int i = 0;
    while(i < 10){
        cout << "Hello" << endl;
        sleep(1);
        ++i;
    }
}
Zera42
  • 2,592
  • 1
  • 21
  • 33