I was trying out some c++11 code, and I tried to write a program that counts down from 10, sleeping in between the outputs. Here's what I have so far:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
std::this_thread::sleep_for(std::chrono::duration<int>(x));
}
int main()
{
for (int x=10; x>0; x--) {
cout << x << "...";
Sleep(1);
}
cout << " FIRE!!\n";
}
The problem is, this code waits 10 seconds and then prints all of the output, instead of counting down from 10. How come this is? And how can I fix it?
(By the way, I tried this on a computer running Linux Mint 17 and MacOSX 10.9, and both times I got the same result)
Probably because you don't flush the output. Try this
cout << x << "..." << flush;
Stream output can be buffered, which means the results don't always appear immediately. Flushing at least increases the chance that you will see some output immediately.
You need to flush the output each time round the loop, otherwise the runtime system will wait for the buffer to be full or (sometimes) an end of line to be sent.
Also, when using std::chrono::duration<>
it is better to use one of the explicitly defined types if possible for readability. In this case you are measuring times in seconds so I used std::chrono::seconds
in your example:
#include <iostream>
using namespace std;
#include <chrono>
#include <thread>
void Sleep(int x)
{
// better to use explicit types for duration
// for readability
std::this_thread::sleep_for(std::chrono::seconds(x));
}
int main()
{
for(int x = 10; x > 0; x--) {
cout << x << "..." << std::flush; // need to flush here
Sleep(1);
}
cout << " FIRE!!\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With