[英]Converting a string to double using c_str() in C++
Is it not reccomended to convert a string in such way: 不建议这样转换字符串:
string input = "81.312";
double val = atof(input.c_str());
DO NOT use std::atof
in C++. 不要在C ++中使用
std::atof
。 That doesn't check for input error. 那不会检查输入错误。
Use std::stod
. 使用
std::stod
。 That checks for error also and throws exception accordingly. 那也检查错误并相应地抛出异常。
Also, it takes std::string const &
as argument. 此外,它还使用
std::string const &
作为参数。 So you don't have to pass input.c_str()
. 因此,您不必传递
input.c_str()
。 Just do this: 只要这样做:
double value = std::stod(input);
It is not wrong, but more right would be to use boost::lexical_cast. 没错,但是使用boost :: lexical_cast更正确。
You should also check if these tools handle NANs and INFs correctly. 您还应该检查这些工具是否正确处理了NAN和INF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.