异常
下面的代码,是我按标准c++写的,但是当输入错误时不能返回到应用程序,而是不断输出错误,郁闷中,不知道怎样才能返回
#include <iostream>
using namespace std;
int main()
{
int a;
while ( 1 )
{
try
{
cin> > a;
}
catch(...)
{
cout < < "exception " < <endl;
}
}
return 0;
}
[解决办法]
#include <iostream>
#include "boost/lexical_cast.hpp "
using namespace std;
int main()
{
int a;
while(1) {
cout < < "请输入整数: " < < endl;
string s;
cin > > s;
try {
a = boost::lexical_cast <int> (s);
break;
} catch(boost::bad_lexical_cast&) {}
}
cout < < a < < endl;
system( "pause ");
return 0;
}
[解决办法]
while(!(cin > > a))
{
cin.clear();
cin.ignore(1000, '\n ');
}