using C++ IO istream object to read is resulting in infinite loop
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
}
精彩评论