Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is explicit flush necessary for interleaved cout and cin operations?

I notice that in many source code files one can see that writing to cout just before reading from cin without an explicit flush:

#include <iostream>
using std::cin; using std::cout;

int main() {
    int a, b;
    cout << "Please enter a number: ";
    cin >> a;
    cout << "Another nomber: ";
    cin >> b;
}

When this executes and the user inputs 42[Enter]73[Enter] it nicely prints (g++ 4.6, Ubuntu):

Please enter a number: 42
Another number: 73

Is this defined behavior, i.e. does the standard say that somehow cout is flushed before cin is read? Can I expect this behavior on all conforming systems?

Or should one put an explicit cout << flush after those messages?

like image 546
towi Avatar asked Jan 12 '23 19:01

towi


1 Answers

The stream std::cout is tied to std::cin by default: the stream pointed to by stream.tie() is flushed prior to every properly implement input operation. Unless you changed the stream tied to std::cin, there is no need to flush std::cout before using std::cin as it will be done implicitly.

The actual logic to flush the stream happens when constructing a std::istream::sentry with an input stream: when the input stream isn't in failure state, the stream pointed to by stream.tie() is flushed. Of course, this assumes that the input operators look something like this:

std::istream& operator>> (std::istream& in, T& value) {
    std::istream::sentry cerberos(in);
    if (sentry) {
        // read the value
    }
    return in;
}

The standard stream operations are implemented this way. When user's input operations are not implemented in this style and do their input directly using the stream buffer, the flush won't happen. The error is, of course, in the input operators.

like image 185
Dietmar Kühl Avatar answered Jan 17 '23 19:01

Dietmar Kühl