溫馨提示×

C++中stod異常處理技巧

c++
小樊
105
2024-07-13 09:20:27
欄目: 編程語言

在C++中,std::stod函數(shù)用于將字符串轉(zhuǎn)換為double類型。如果轉(zhuǎn)換失敗,會(huì)拋出std::invalid_argument異常。以下是一些處理std::invalid_argument異常的技巧:

  1. 使用try-catch語句捕獲異常:
try {
    std::string str = "abc";
    double num = std::stod(str);
} catch (const std::invalid_argument& e) {
    std::cerr << "Invalid argument: " << e.what() << std::endl;
}
  1. 使用std::stod函數(shù)的返回值檢查是否成功轉(zhuǎn)換:
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;
}
  1. 使用異常安全的方式處理轉(zhuǎn)換:
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函數(shù)時(shí)更好地處理std::invalid_argument異常。

0