开发者

using C++ IO istream object to read is resulting in infinite loop

开发者 https://www.devze.com 2022-12-14 15:41 出处:网络
The below functionresults in infinite loop if a string is entered as input. istream & inputFunc(istream &is)

The below function results in infinite loop if a string is entered as input.

istream & inputFunc(istream &is)
{
   int ival;
    // read cin and test only for EOF; loop is executed even if there are other IO failures
    while (cin >> ival, !cin.eof()) {
        if (cin.bad())         // input stream is corrupted; bail out
            throw runtime_error("IO stream corrupted");
        if (cin.fail()) {                        // bad input
            cerr<< "bad data, try again";        // warn the user
            cin.clear(istream::failbit);         // reset the stream
            continue;                            // get next input
        }
        // ok to process ival
        cout << "you entered: " << ival << endl;
    }



}

The below function results in infinite loop if a string is entered as input.

OUTPUT:

try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad d开发者_运维百科ata, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data, try againbad data,


You need to do two things:

1) clear state like here: cin.clear(istream::goodbit);

2) skip one char at a time after clearing the state, because you don't know where the next number starts:

 char c;
 cin >> c;


Yes, it does loop infinitely. Look at cin.clear().


Is the bad data still sitting in the input stream? If so, something like this might help:

    if (cin.fail()) {                        // bad input
        string badData;                      // create a string to hold the bad input
        cin.clear(istream::failbit);         // reset the stream
        cin >> badData;                      // read the bad input to clear the stream
        cerr<< "bad data: " << badData << ", try again"; // warn the user
        continue;                            // get next input
    }
0

精彩评论

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

关注公众号