tags:

views:

275

answers:

4

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); 
} 
+2  A: 

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); 
} 
Ben Burnett
considering the linux tag on the question, I would assume that including <windows.h> is not an option
BennyG
+4  A: 

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

Dave Kilian
ahhh, interesting.
Dalton Conley
<< endl actually flushes the stream. It has the same effect as << "\n" << flush.
Amardeep
Or you can use std::ends to do the same thing without the newline.
Konrad
A: 

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.

Nikko
A: 

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.

Mark B