流状态的查询和控制
在学习中,碰到书中这样一个例子,自己写了一个小程序实现它,如下:
#include <iostream>
using namespace std;
int main()
{
int ival;
// read com amd test only for EOF: loop is executed if there are other IO failures
while (cin >> ival , !cin.eof())
{
if (cin.bad()) // input stream is corrupted; baid out
{
throw runtime_error("TO 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
}
}
return 0;
}
当运行时,如果输入的是int类型,则允许下一次输入,当输入错误时,则一直显示bad data, try again,成为一个死循环。单步调试时,发现当输入错误时,则不允许下次输入,直接跳过了。搞不清楚为什么,迷惑中。
如果去掉!cin.eof(),则直接判断,错误时就跳出循环,结束。