简体   繁体   中英

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

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

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.

#include <iostream>
using namespace std;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM