Shoe
Shoe

Reputation: 76300

It doesn't sleep as expected

Considering that this prints something like

[E] [F] [A] [C] [A] 
[B] [F] [B] [B] [D] 
[C] [C] [C] [C] [C]

The following wait 5 seconds and print a row instead of executing each [...] and wait 1 second, why?

    for (int i = 0; i <= 2; i++) {
        for (int j = 0; j <= 4; j++) {
            int a = randomInt(0, 5);
            sleep(1);
            cout << "[" << allowed[a] << "] ";
            usciti[i][j] = allowed[a];
        }
        cout << endl;
    }

Upvotes: 0

Views: 221

Answers (3)

ezdazuzena
ezdazuzena

Reputation: 6790

This should work:

for (int i = 0; i <= 2; ++i) {
    for (int j = 0; j <= 4; ++j) {
        int a = randomInt(0, 5);
        sleep(1);
        cout << "[" << allowed[a] << "] " << std::flush;
        usciti[i][j] = allowed[a];
    }
    cout << endl;
}

Like this you flush the cout. cout << endl; will then just start a new line.

In your code you are writing to the buffer, until flushing it with endl (plus adding a new line). For details see here.

Upvotes: 3

psur
psur

Reputation: 4519

Maybe output is buffered? Look at this function: http://www.cplusplus.com/reference/iostream/ostream/flush/

Upvotes: 1

Dennis
Dennis

Reputation: 3741

It's probably because you are not flushing the std::cout stream until the endl (which flushes as well). You could use a call to cout.flush() to do that.

Upvotes: 6

Related Questions