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

耗尽温柔 提交于 2019-12-30 23:21:31

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26818807/is-it-possible-to-read-an-empty-string-from-cin-and-still-get-true-from-cin-good

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!