I am learning C++ Primer 4th edition now and playing with IO stream. When I tried to run the code in the book (Page 289):
#include <iostream>
#include <string>
using namespace std;
int main()
{
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()){
cerr << "bad data, try again\n";
cin.clear(istream::failbit);
continue;
}
//ok to process ival
}
}
I met an infinite loop after typing a string (say "as"). So what is wrong with this code?