开发者

Istream fails. What is the safe way to use it!

开发者 https://www.devze.com 2023-02-20 12:22 出处:网络
So I am wondering what happens if I have the following code 开发者_如何学Pythonint i; cin>> i;

So I am wondering what happens if I have the following code

开发者_如何学Pythonint i;
cin>> i;

But I actually entered "abc" instead of an integer. It fails? What are the ways to make sure reading from commmand line does not fail?


The fail bit of the stream will be set, and further operations will do nothing until the bit is cleared. You can read more about stream bits here.

If you don't want it to fail, simply check the bit:

int i;
std::cin >> i;

if (!std::cin)
{
    // didn't read correctly, handle it
}

Or in one fell-swoop:

int i;

if (!(std::cin >> i))
{
    // didn't read correctly, handle it
}

There may be more robust ways of gathering input, but what you want depends on your situation.


Almost by definition, you can't ensure that reading from the command line doesn't fail. To do that, you'd have to control what was being typed in on the keyboard (or was in the file or whatever the input was redirected from). You have to be prepared for errors in that input. If you need an int, and the user types in "abc", you need the input to fail, so that you can detect the error and recover.

In the input stream, once the error has been detected, you have to reset it (std::cin.clear()), then resynchronize in some way: the "abc" is still in the stream, and will be the next thing you read---depending on the application, istream::ignore can be used, but one frequent idiom for handling console input is to read line by line, then parse the line using a combination of std::istringstream, boost::regex or any other tools you happen to have handy. If the line should just contain a single int, this is overkill: std::cin.ignore( INT_MAX, '\n' ) should do the trick nicely, but for lines with several fields, the line by line approach is probably preferable; it also has the advantage of distinguishing failure because of end of file from syntax errors automatically. (Failure of the getline on std::cin is end of file; failure when reading the istringstream is normally a syntax error.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号