使用C++中的c_str()将字符串转换为double

Jos*_*osh 1 c++ string double

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

string input = "81.312";
double val = atof(input.c_str());
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 11

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

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

此外,它需要std::string const &作为参数.所以你不必通过input.c_str().这样做:

double value = std::stod(input);
Run Code Online (Sandbox Code Playgroud)