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