在 C++ 中转换为双精度时处理异常
handling exception while converting to double in c++
>我正在从文本文件中读取数据,我需要从文件中读取双精度值。现在的问题是,如果双精度值无效,例如"!@#$%^&*",那么我希望我的程序给出异常,以便我可以处理它。这是我的代码
void Employee::read(istream &is) {
try{
is.get(name, 30);
is >> salary;
char c;
while(is.peek()=='n')
is.get( c );
}
catch(exception e){
}
}
下面是验证双输入的可运行示例。
#include<iostream>
#include<sstream>
#include<limits>
using std::numeric_limits;
int main(){
std::string goodString = "12.212", badString = "!@$&*@";
std::istringstream good(goodString), bad(badString);
double d1=numeric_limits<double>::min(),
d2=numeric_limits<double>::min();
std::string tmp;
good >> d1;
if (d1 == numeric_limits<double>::min()) {
// extraction failed
d1 = 0;
good.clear(); // clear error flags to allow further extraction
good >> tmp; // consume the troublesome token
std::cout << "Bad on d1n";
} else std::cout << "All good on d1n";
if (d2 == numeric_limits<double>::min()) {
d2 = 0;
bad.clear();
bad >> tmp;
std::cout << "Bad on d2n";
} else std::cout << "All good on d2n";
}
产生的输出是..
在 d1 上都很好
在 d2 上不好
我终于通过为 istream 设置异常位来使其工作
is.exceptions(ios::failbit | ios::badbit); //setting ifstream to throw exception on bad data
相关文章:
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 有没有更好的方法来处理异常? try-catch块真的很丑
- VisualC++ 2010 有没有办法找出有关未处理异常错误的更多详细信息
- 在析构函数内部处理异常(但不抛出)
- C++ 程序中双链表的未处理异常
- 抛出字符但捕获整数:如何处理异常的促销和转化
- C++ 异常处理:异常与 ifstream::failure
- 防止线程在处理异常后在分离时调用 std::terminate()
- 当数字可能超出C++中特定数据类型的范围时如何处理异常?
- 运算符重载时未处理<<异常
- 实验室中0x6BE20E11 (ucrtbased.dll) 的未处理异常.exe: 0xC0000005:访问冲突读取
- objective-C或ObjectiveC++能处理C++异常吗
- 如何处理异常,使我的程序仍然运行
- ImageMagick 的未处理异常
- 类数组大小为的未处理异常
- 尝试将构造函数设置为 0 - c++ 的未处理异常
- C - 处理异常而不会丢失呼叫箱
- 在分配scoped_ptr之前处理异常
- C++异常处理如何处理异常派生类
- Dijkstra 中0x001e1078 s_Algorithm.exe的未处理异常:0xC0000005:访问冲突读取位置0xbaadf00d