user3821372
user3821372

Reputation: 23

While loop executing too early in C++

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?

Upvotes: 2

Views: 311

Answers (3)

Lasse Reinhold
Lasse Reinhold

Reputation: 166

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

Upvotes: 0

zdan
zdan

Reputation: 29450

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;

Upvotes: 3

Paul Evans
Paul Evans

Reputation: 27567

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;

Upvotes: 4

Related Questions