Peter
Peter

Reputation: 2320

Is it possible to read an empty string from cin and still get true from cin.good()?

My question is based on this simple code:

#include <string>
using namespace std;

int main() {
    string buf;
    while (cin >> buf && !buf.empty()) {
        cout << "input is " << buf << "\n";
    }

    return 0;
}

The operator>> of cin (which is an object of type basic_istream) reads and discards any leading whitespace (e.g. spaces, newlines, tabs). Then operator>> reads characters until the next whitespace character is encountered. The operators returns finally the stream itself, cin.
It shouldn't be possible to enter an empty string without also setting at least one of the iostates eof, fail or bad? And therefore the streams converts with the operator bool to false. I think !buf.empty() is here superfluous, but a good habit. Is there a way to leave the iostate of cin in good and leaving the string empty?

Example usage:
1. type in a word of your choice
2. press enter
3. press Ctrl+d (EOF on UNIX) or Ctrl+d (EOF on Windows)

Thank you

Upvotes: 4

Views: 1460

Answers (1)

Columbo
Columbo

Reputation: 60999

No, it is not possible. If no characters could be extracted std::ios::failbit is set. [string.io]/3:

If the function extracts no characters, it calls is.setstate(ios::failbit), which may throw ios_base::failure.

And if characters could be extracted they are subsequently appended to the string and thereby make its size non-zero.

Upvotes: 5

Related Questions