按照《C++ Primer》使用cin.fail()时出现了死循环
代码如下,如果输入
2
3
ab
则会无限循环,怎么回事?如何解决?编译器是VS 2008
c++ cin.fail()
#include <iostream>
using std::runtime_error;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
void keep_window_open();
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())
{
try
{
if (cin.bad()) // input stream is corrupted; bail out
throw runtime_error("IO stream corrupted!");
}catch(runtime_error err)
{
cout<<err.what()<<endl;
}
if (cin.fail()) // bad input
{
cerr<< "bad data, try again: "; // warn the user
cin.clear(std::istream::failbit); // reset the stream
continue; // get next input
}
// ok to process ival
}
keep_window_open();
}
void keep_window_open()
{
cout << "\nPress any key to exit:";
getchar();
}