在C++中,std::stod
函数用于将字符串转换为double类型。如果转换失败,会抛出std::invalid_argument
异常。以下是一些处理std::invalid_argument
异常的技巧:
try {
std::string str = "abc";
double num = std::stod(str);
} catch (const std::invalid_argument& e) {
std::cerr << "Invalid argument: " << e.what() << std::endl;
}
std::stod
函数的返回值检查是否成功转换:std::string str = "123.45";
try {
size_t pos;
double num = std::stod(str, &pos);
if (pos < str.size()) {
std::cerr << "Invalid argument: Not all characters were converted" << std::endl;
}
} catch (const std::invalid_argument& e) {
std::cerr << "Invalid argument: " << e.what() << std::endl;
}
double stringToDouble(const std::string& str) {
try {
return std::stod(str);
} catch (const std::invalid_argument& e) {
std::cerr << "Invalid argument: " << e.what() << std::endl;
return 0.0; // or any other default value
}
}
std::string str = "123.45";
double num = stringToDouble(str);
这些技巧可以帮助您在使用std::stod
函数时更好地处理std::invalid_argument
异常。