C ++, sleep and loops

Well, it's just out of curiosity, but why does the sleep function NOT work in a loop, or how can I make it work in a loop?

for(int i = 0; i < 5; i++) { 
     cout << i << endl; 
     sleep(2); 
} 
+3
source share
6 answers

coutIt is buffered, that is, its contents are not always written to the console immediately. Try adding cout.flush()right beforesleep(2);

+6
source

If this does not work for you, you can try this code:

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

...

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

, . , std:: cout - ? sleep() ( )? ? .

0

, , ?

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

, , std:: endl , , dave.kilian , cout , () .

std:: flush , - , ( ?) .

, - , tail -f . , .

, , .

0

Dave has already given you the answer, so I wonโ€™t touch it. However, if its pure for debugging or prototype code, you can also pass the output to std :: cout sibling, std :: cerr, which is unbuffered to start with. This means that you do not need to explicitly call flush, and you do not need to add endl to your output.

0
source

Try Sleep () instead of sleep ()

-1
source

Source: https://habr.com/ru/post/1748456/


All Articles