For converting a string to a floating-point number in C++, it's now (since the standardization of C++11) advisable to use one of std::stof
, std::stod
and std::strold
(where these functions had been added to the C++ standard library):
std::string s = "120.0";
float f = std::stof(s);
double d = std::stod(s);
long double ld = std::stold(s);
The primary reason to prefer these functions over those in the C standard library is safety:
they don't operate on raw pointers but string objects (that also leads to a minor improvement in convenience and readability: one does not have to call c_str()
over and over again when working with std::string
s); and
they don't exhibit undefined behavior when the conversion is impossible (they predictably throw well-documented exceptions instead).