I'm trying to convert std::string
to float/double
.
I tried:
std::string num = "0.6";
double temp = (double)atof(num.c_str());
But it always returns zero. Any other ways?
I'm trying to convert std::string
to float/double
.
I tried:
std::string num = "0.6";
double temp = (double)atof(num.c_str());
But it always returns zero. Any other ways?
The Standard Library (C++11) offers the desired functionality with
std::stod
:I guess the Standard Library converts internally too, but this way makes the code cleaner. Generally for most other basic types, see
<string>
. There are some new features for C strings, too. See<stdlib.h>
You can use boost lexical cast:
Note: boost::lexical_cast throws exception so you should be prepared to deal with it when you pass invalid value, try passing string("xxx")
Lexical cast is very nice.
If you don't want to drag in all of boost, go with
strtod(3)
from<cstdlib>
- it already returns a double.Outputs:
Why atof() doesn't work ... what platform/compiler are you on?
You don't want Boost lexical_cast for string <-> floating point anyway. That subset of use cases is the only set for which boost consistently is worse than the older functions- and they basically concentrated all their failure there, because their own performance results show a 20-25X SLOWER performance than using sscanf and printf for such conversions.
Google it yourself. boost::lexical_cast can handle something like 50 conversions and if you exclude the ones involving floating point #s its as good or better as the obvious alternatives (with the added advantage of being having a single API for all those operations). But bring in floats and its like the Titanic hitting an iceberg in terms of performance.
The old, dedicated str->double functions can all do 10000 parses in something like 30 ms (or better). lexical_cast takes something like 650 ms to do the same job.
I had the same problem in Linux
it works.