cout does not print even with time delay

494 Views Asked by At

I expect cout to print "hello" and two seconds later " world".

int t = time( NULL );

std::cout << "hello";

while( time(NULL) < (t + 2) );

std::cout << " world";

But instead, cout prints noting to screen until after two seconds later, then the program prints "hello world". Even if the time delay increases like (t + 9), it is the same result. I Am not familiar with this cout behaviour.

But if I add std::endl at the first cout like so:

std::cout << "hello" << std::endl;
...

I get the expected result "hello" and two seconds later " world ".

1

There are 1 best solutions below

1
On BEST ANSWER

std::cout is usually buffered, meaning it may not output immediately unless you force it to. Try std::flush after your first output:

std::cout << "hello " << std::flush;