在 C++ 中使用 c_str() 将字符串转换为双精度

Converting a string to double using c_str() in C++

本文关键字:字符串 转换 双精度 str C++      更新时间:2023-10-16

不建议以这种方式转换字符串:

string input = "81.312";
double val = atof(input.c_str());
不要

在C++中使用std::atof。这不会检查输入错误。

使用 std::stod .这也检查错误并相应地抛出异常。

此外,它以std::string const &作为论据。所以你不必通过input.c_str().只需这样做:

double value = std::stod(input);

这没有错,但更正确的是使用 boost::lexical_cast。

还应检查这些工具是否正确处理 NAN 和 INF。