
急!!!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,怎样才能让它提示错误而不是进入死循环。 展开
#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,怎样才能让它提示错误而不是进入死循环。 展开
展开全部
#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;
}
#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;
}
使用这个 刚刚没有清空输入流 ,那就是输出错误的类型
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询