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

标签 c++ file exception

我正在从文本文件中读取数据,我需要从文件中读取 double 值。现在的问题是,如果 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){
    }
}

最佳答案

这是一个验证双重输入的可运行示例。

#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";
}

产生的输出是..

All good on d1

Bad on d2

关于c++ - 在 C++ 中转换为 double 时处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10661321/

相关文章:

c++ - 这个模式在 C++ 中有效吗?

c++ - 如何正确删除从另一个 DLL 接收的派生对象?

java - 设置文本表 hsqldb Java

c++ - 在 C++ 中包含文件?

python - 在 Python 3 中逐行读取文件时捕获 UnicodeDecodeError 异常

C++ - 值意外更改

c++ - C++对象声明中第四列的字符串

java - poi jar 文件 java.lang.NoSuchMethodError 问题

android - onActivityResult 的 intent.getPath() 没有给我正确的文件名

Java 如何将 "Override"设为一个 catch block