John
John

Reputation: 153

C++ first sleeps than "couts"

I am just learning c++ and been playing with sleep() function, this is my code

#include<iostream>
#include<unistd.h>
using namespace std;
int main(){
cout << "...";
sleep(5)
cout << "\nLorem Ipsum"
}

instead of output being

...

and than after five seconds

Lorem Ipsum

instead I get five second wait first and than this is printed all at once

...
Lorem Ipsum

Upvotes: 2

Views: 90

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You should flush() cout explicitly (or use std::endl) to force immediate output

int main() {
    cout << "...";
    cout.flush(); // Flush explicitly
    sleep(5):
    cout << "\nLorem Ipsum";
}

The text will not be written to std::cout, unless the underlying buffer has reached a certain watermark filling, or std::flush() is called (std::endl does so implicitly).

Upvotes: 4

Related Questions