Dalton Conley
Dalton Conley

Reputation: 1615

c++, sleep, and loops

Ok, this is just out of curiousity, but why does the sleep function NOT work in a loop, or how can I Get it to work in a loop?

for(int i = 0; i < 5; i++) { 
     cout << i << endl; 
     sleep(2); 
} 

Upvotes: 3

Views: 9337

Answers (6)

Carl
Carl

Reputation: 44448

Dave has already given you the answer, so I won't touch on that. However, if its purely for debugging or prototype code, you could also pipe the output to std::cout's sibling, std::cerr, which is unbuffered to begin with. This means you do not need to call flush explicitly and you do not need to add an endl to your output.

Upvotes: 0

andyc
andyc

Reputation: 525

Try Sleep() instead of sleep()

Upvotes: -2

Nikko
Nikko

Reputation: 4252

In my humble opinion, this program should work correctly. Maybe your std::cout is redirected somewhere else? You don't call the correct sleep() function (but no header provided)? Or other problem? But it should work.

Upvotes: 0

Mark B
Mark B

Reputation: 96241

Have you tried unrolling the loop to see if that behaves the same way?

cout << 1 << endl;
sleep(2);
cout << 2 << endl;
sleep(2);
// Etc.

Assuming that behaves the same way, even though std::endl is supposed to flush the buffer, it really does look like dave.kilian has the right idea that cout isn't getting flushed until the program (presumably) terminates.

In that case, try doing the std::flush and see if that helps - it's possible you have a bug (missed feature?) in your standard library.

Another thing to try is to redirect the output to a file while watching it with tail -f in another window. See if the same delay occurs when redirected.

Finally try playing with the compiler's optimization level and see if that changes the results.

Upvotes: 0

Dave Kilian
Dave Kilian

Reputation: 1012

cout is buffered, meaning its contents aren't always written to the console right away. Try adding cout.flush() right before sleep(2);

Upvotes: 6

Ben Burnett
Ben Burnett

Reputation: 1564

If that isn't working for you you could try this code:

#include <iostream>
#include <windows.h>

...

for(int i = 0; i < 5; i++) { 
     cout << i << endl; 
     Sleep(2000); 
} 

Upvotes: 1

Related Questions