关于排序异常的问题
时间:2011-12-04
来源:互联网
对输入的int型整数进行排序,代码如下
问题1:当输入小数时会发生无限循环,除非我定义一个ERROR_DETECT将异常抛出,为何?难道是push_back()的问题?
问题2:在没有显示的if(!cin)语句情况下,为啥catch不到错误?
求指教~
#include <iostream>
#include <exception>
#include <vector>
#include <algorithm>
#define ERROR_DETECT
using namespace std;
int main(){
try{
vector<int> numbers;
do{
cout<<"next whole number(-999 to stop): ";
int next;
cin>>next;
#ifdef ERROR_DETECT;
if(!cin)
throw exception();
#endif
if(next==-999)
break;
numbers.push_back(next);
}while(true);
if(numbers.size()==0){
cout<<"There were no numbers input.\n";
return 0;
}
sort(numbers.begin(),numbers.end());
cout<<"Here are the"<<numbers.size ()<<"numbers you typed in a asceding numerical order: \n";
for(int i(0);i!=numbers.size ();i++)
cout<<numbers[i]<<",";
cout<<endl;
}
catch(...){
cerr<<"***An exception was thrown.***\n";
}
}
问题1:当输入小数时会发生无限循环,除非我定义一个ERROR_DETECT将异常抛出,为何?难道是push_back()的问题?
问题2:在没有显示的if(!cin)语句情况下,为啥catch不到错误?
求指教~
#include <iostream>
#include <exception>
#include <vector>
#include <algorithm>
#define ERROR_DETECT
using namespace std;
int main(){
try{
vector<int> numbers;
do{
cout<<"next whole number(-999 to stop): ";
int next;
cin>>next;
#ifdef ERROR_DETECT;
if(!cin)
throw exception();
#endif
if(next==-999)
break;
numbers.push_back(next);
}while(true);
if(numbers.size()==0){
cout<<"There were no numbers input.\n";
return 0;
}
sort(numbers.begin(),numbers.end());
cout<<"Here are the"<<numbers.size ()<<"numbers you typed in a asceding numerical order: \n";
for(int i(0);i!=numbers.size ();i++)
cout<<numbers[i]<<",";
cout<<endl;
}
catch(...){
cerr<<"***An exception was thrown.***\n";
}
}
作者: woshishuizzz 发布时间: 2011-12-04
1.这个排序无关,跟cin对输入的处理有关,push_back不是问题所在
2.cin不认为那是个异常
2.cin不认为那是个异常
作者: mstlq 发布时间: 2011-12-04
期待整数但输入了浮点数时,cin认为是一个failure,但不是exception,所以if(!cin)可以
作者: yisikaipu 发布时间: 2011-12-04
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28