在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
異常。