1

I need a timer that does X every second. I made this, however it doesn't print anything until the program is terminated, I find that weird. It prints everything after three seconds if you put three as the counter, and 100 if you chose that.

How do make it print every second and not all at once at termination?

int main()
{
    using namespace std;
    //Number to count down from
    int counter = 10;
    //When changed, a second has passed
    int second = (unsigned)time(NULL);
    //If not equal to each other, counter is printed
    int second_timer = second;
    while (counter > 0) {
        second = (unsigned)time(NULL);
        while (second != second_timer) {
            //Do something
            cout << counter-- << ", ";
            //New value is assigned to match the current second
            second_timer = second;
        }
    }
    cout << "0" << endl;
    return 0;
}
Lemonizer
  • 83
  • 2
  • 4
  • 14
  • 1
    Using up all of the CPU while you wait for a timeout really isn't a solution. Anyway, this has nothing to do with timers. `std::cout` is buffered. – chris May 30 '13 at 19:55

2 Answers2

2

Add << flush where you want to flush. I.e. change your printout to:

cout << counter-- << ", " << flush;

champagniac
  • 444
  • 3
  • 4
1

endl causes the buffer to 'flush' and be written out to stdout. You can add << endl; to your cout << counter--, manually flush the cout stream using cout.flush();, or append << flush; to the end of your cout expression (thanks @Rob!)

For more info, the answer to this question seems to go into more detail.

Community
  • 1
  • 1
Rollie
  • 4,391
  • 3
  • 33
  • 55