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 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,