帮我看下这个C++代码的问题在哪

来源:百度知道 编辑:UC知道 时间:2024/06/06 10:17:11
#include <iostream>
#include <string>
#include <stdexcept>

using std::cin;
using std::cout;
using std::cerr;
using std::string;
using std::endl;
using std::istream;
using std::runtime_error;

main()
{
int val;
while(cin>>val,!cin.eof())
{
if(cin.bad())
{
throw runtime_error("IO stream corrupted!!!");
break;
}
if(cin.fail())
{
cerr<<"bad data,try again!!"<<endl;
cin.clear(istream::failbit);
continue;
}
}
system("pause");
}

如果我输入了一个非整型的数值,cin将生成一个错误状态,为什么我调用了clear函数不能将输入流的状态恢复成有效的啊?
这是C++ P

int main()
{
int val;
while(cin>>val,!cin.eof())
{
if(cin.bad())
{
throw runtime_error("IO stream corrupted!!!");
break;
}
if(cin.fail())
{
cerr<<"bad data,try again!!"<<endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
continue;
}
cout << val << endl;
}
system("pause");
}

#include <iostream>
#include <string>
#include <stdexcept>

using std::cin;
using std::cout;
using std::cerr;
using std::string;
using std::endl;
using std::istream;
using std::runtime_error;

main()
{
int val;
while(cin>>val,!cin.eof())
{
if(cin.bad())
{
throw runtime_error("IO stream corrupted!!!"