Haris
Haris

Reputation: 14053

Cout in While loop Strange behaviour

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?.

Upvotes: 1

Views: 169

Answers (3)

Zera42
Zera42

Reputation: 2692

#include <iostream>
using namespace std;

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

Upvotes: 0

Antimony
Antimony

Reputation: 39451

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.

Upvotes: 1

Felice Pollano
Felice Pollano

Reputation: 33252

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

Upvotes: 4

Related Questions