在c ++中转换为double时处理异常

时间:2012-05-19 00:26:10

标签: c++ file exception-handling

我正在从文本文件中读取数据,并且需要从文件中读取双值。现在的问题是,如果double值无效,例如“!@#$%^& *”,那么我希望我的程序提供异常,以便我可以处理它。这是我的代码

void Employee::read(istream &is) {
    try{

        is.get(name, 30);
        is >> salary;
        char c;

        while(is.peek()=='\n')
            is.get( c ); 

    }
    catch(exception e){
    }
}

2 个答案:

答案 0 :(得分:3)

以下是验证 double 输入的可运行示例。

#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 d1\n";
    } else std::cout << "All good on d1\n";

    if (d2 == numeric_limits<double>::min()) {
      d2 = 0;
      bad.clear();
      bad >> tmp;
      std::cout << "Bad on d2\n";
    } else std::cout << "All good on d2\n";
}

产生的输出是..

  

d1的所有优点

     

在d2上不好

答案 1 :(得分:2)

我终于通过为istream

设置异常位来使其工作
is.exceptions(ios::failbit | ios::badbit);  //setting ifstream to throw exception on bad data