急!!!C++中关于数据类型的异常处理。

例如#include<iostream>usingnamespacestd;voidmain(){intn;while(1){cout<<"inputn"<<endl;c... 例如
#include<iostream>
using namespace std;
void main()
{
int n;

while(1)
{
cout<<"input n"<<endl;
cin>>n;
switch(n)
{
case 21:
{
cout<<n<<endl;
}break;
case 0:
{
return;
}break;
default:
{
cout<<"wrong number !"<<endl;
}
}
}
}
假如再输入n是误输入了a,怎样才能让它提示错误而不是进入死循环。
展开
 我来答
xyz216909
2011-12-24 · 超过19用户采纳过TA的回答
知道答主
回答量:47
采纳率:100%
帮助的人:59.1万
展开全部
#include<iostream>
#include<string>
#include<stdexcept>
using namespace std;
int main()
{
int n;

while(1)
{
cin.clear();
cout<<"qing shu ru yi ge zhengshu:";
cin>>n;
try
{
if(!cin)
{
throw runtime_error("the wrong input");

}
else
{
switch(n)
{
case 21:
{
cout<<n<<endl;
}break;
case 0:
{
return -1;
}break;
default:
{
cout<<"wrong number !"<<endl;
}

break;
}
break;
}
}

catch(runtime_error err)
{

cin.clear();
cout<<err.what()<<"\nTry again? Enter y or n"<<endl;
string c;
cin>>c;
if(c=="n")
break;

}

}

return 0;
}
追问
cin.clear();
cout<<err.what()<<"\nTry again? Enter y or n"<<endl;
这些语句是什么意思?运行时并没有让我输入y或n,他是直接运行的。
追答
#include
#include
#include
#include
using namespace std;
int main()
{
int n;

while(1)
{
cin.clear();
cout>n;
try
{
if(!cin)
{
throw runtime_error("the wrong input");

}
else
{
switch(n)
{
case 21:
{
cout::max(),'\n');
cout>c;
if(c=="n")
break;

}

}

return 0;
}
使用这个 刚刚没有清空输入流 ,那就是输出错误的类型
13859381268
2011-12-24
知道答主
回答量:65
采纳率:0%
帮助的人:10.7万
展开全部
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式