std::string to float or double

2019-01-02 15:11发布

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?

标签: c++
15条回答
公子世无双
2楼-- · 2019-01-02 15:42

The Standard Library (C++11) offers the desired functionality with std::stod :

std::string  s  = "0.6"
std::wstring ws = "0.7"
double d  = std::stod(s);
double dw = std::stod(ws);

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>

查看更多
后来的你喜欢了谁
3楼-- · 2019-01-02 15:45

You can use boost lexical cast:

#include <boost/lexical_cast.hpp>

string v("0.6");
double dd = boost::lexical_cast<double>(v);
cout << dd << endl;

Note: boost::lexical_cast throws exception so you should be prepared to deal with it when you pass invalid value, try passing string("xxx")

查看更多
看淡一切
4楼-- · 2019-01-02 15:48

Lexical cast is very nice.

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>

using std::endl;
using std::cout;
using std::string;
using boost::lexical_cast;

int main() {
    string str = "0.6";
    double dub = lexical_cast<double>(str);
    cout << dub << endl;
}
查看更多
伤终究还是伤i
5楼-- · 2019-01-02 15:49

If you don't want to drag in all of boost, go with strtod(3) from <cstdlib> - it already returns a double.

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;

int main()  {
    std::string  num = "0.6";
    double temp = ::strtod(num.c_str(), 0);

    cout << num << " " << temp << endl;
    return 0;
}

Outputs:

$ g++ -o s s.cc
$ ./s
0.6 0.6
$

Why atof() doesn't work ... what platform/compiler are you on?

查看更多
低头抚发
6楼-- · 2019-01-02 15:49

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.

查看更多
有味是清欢
7楼-- · 2019-01-02 15:55

I had the same problem in Linux

double s2f(string str)
{
 istringstream buffer(str);
 double temp;
 buffer >> temp;
 return temp;
}

it works.

查看更多
登录 后发表回答