c++

如何处理C++ stod的转换错误

小樊
89
2024-07-13 09:26:27
栏目: 编程语言

在处理C++中 stod 转换错误时,可以使用 try-catch 块来捕获异常。例如:

try {
    std::string str = "123.45";
    double num = std::stod(str);
    std::cout << "Converted number: " << num << std::endl;
} catch (std::invalid_argument& e) {
    std::cerr << "Invalid argument: " << e.what() << std::endl;
} catch (std::out_of_range& e) {
    std::cerr << "Out of range: " << e.what() << std::endl;
} catch (...) {
    std::cerr << "Unknown error occurred" << std::endl;
}

在这个例子中,我们使用 try-catch 块来捕获可能出现的异常,包括 invalid_argument、out_of_range 和其他未知异常。通过捕获异常,我们可以在程序出现转换错误时进行相应的处理,比如输出错误信息或者采取其他措施。

0
看了该问题的人还看了