2

I wrote a simple program based on that from Chapter 5, listing 5.14 from C++ Primer 5th edition, supposedly meant to take an input time from a user and make the programe "wait" for that amount of time in seconds. The program does so using a while loop and although the waiting duration is correct, the order that the statements execute in is not on my system (Ubuntu 14.04 with g++ compiler). I wrote in a cout statement that should occur BEFORE the while loop. Currently it only ever executes after the while loop despite being before this loop in my code. I'm unsure how to resolve this problem...

//Program to wait a certain number of seconds
//Also introduces the "while" loop

#include <iostream>
#include <ctime>

int main()
{
    using namespace std;
    float seconds;

    cout << "\nEnter the number of seconds you wish to wait for: ";

    cin >> seconds; 
    cout << "\n\nStarting countdown...\a";

    //clock_t is a variable type! It's in terms of system clock units though, NOT seconds

    clock_t delay = seconds * CLOCKS_PER_SEC;
    clock_t start = clock();

    while (clock() - start < delay);

    cout <<"\a and done!\n\n";

    return 0;
}

The output I get after putting in the number of seconds to wait for is the system blinking the cursor for the amount of time I input followed by "Starting countdown... and done!" all at once. Any ideas?

  • 4
    `cout` is buffered. Use `cout.flush()` to ensure that the whole buffer has been printed. – clcto Jul 09 '14 at 16:53

3 Answers3

4

You want to flush cout's buffers, something like:

cout << "\n\nStarting countdown...\a" << endl;

or, if you don't want a carrage return just use:

cout << "\n\nStarting countdown...\a" << flush;

or

cout.flush();

after the output;

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
3

The output stream will buffer its output until it is flushed. You can flush it manually to make sure you see the output when you expect it:

cout << "\n\nStarting countdown...\a" << flush;
zdan
  • 28,667
  • 7
  • 60
  • 71
0

You can also simply output to cerr instead of cout, then there's no need to flush explicitly because it flushes automatically.