首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

错误

2012-04-13 
异常下面的代码,是我按标准c++写的,但是当输入错误时不能返回到应用程序,而是不断输出错误,郁闷中,不知道

异常
下面的代码,是我按标准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 ');
}

热点排行