I have a function that pauses the console for a few seconds and then continues to the next function:
void esperar(double segundos){
if(segundos < 0) return;
#ifdef _WIN32
segundos *= 1000;
int goal = (int) segundos + clock();
while(goal > clock());
#else
segundos *= 1000000;
int goal = (int) segundos;
usleep(goal);
#endif
}
Assuming I want to print the numbers 1 to 10 with a for loop I get two different answers depending on whether there is a line break or not.
for(int i = 0; i < 10; ++i){
cout << i + 1 << " ";
esperar(0.1);
}
In the first loop I leave a space after each number, but this loop waits a tenth of a second (0.1 * 1000000) for each cout in the loop, for a total of 1 second. Only until the 10 cycles of 0.1 seconds are finished is the string printed.
1 2 3 4 5 6 7 8 9 10
In the second loop I leave a line break between each number.
for(int i = 0; i < 10; ++i){
cout << i + 1 << endl;
esperar(0.1);
}
But this has a different (and desired) behavior. After printing the first cout the console waits 0.1 seconds to print the second cout, waits 0.1 seconds and prints the next one....
1
//0.1 segundos
2
//0.1 segundos
3
//0.1 segundos
4
//0.1 segundos
5
//0.1 segundos
[...]
I have the following libraries included
#include<time.h>
#include<unistd.h>
Is there a way to correct this?
In the first version you use a space as a separator:
What is happening here is that you are accumulating in the output buffer a sequence of numbers. Accumulating them in the output buffer does not imply that they are being displayed on the screen. The buffer is not synchronous with the console.
At a given moment a synchronization will be forced (because the program ends, a call to a data input method is made, ...) and then the content of the buffer will be dumped to the screen.
In this case I assume that the results will be displayed on the screen after a wait of 1 second (0.1 seconds of waiting for 10 numbers to be displayed).
If we now see the second case:
You are now calling
endl
. Although itendl
introduces, as we all know, a line break, this element has another added functionality and that is that it forces the output buffer to be synchronized. This forces that, after entering a number in the buffer, it is dumped to the console.For the reason mentioned above, in the second case you observe that between the appearance of each number there is a wait of 0.1 seconds.
I imagine that what you want is to correct the first case. To force output buffer synchronization you can use
std::flush
: