views:

569

answers:

2

Hi, I've got a database filled up with doubles like the following one:

1.60000000000000000000000000000000000e+01

Does anybody know how to convert a number like that to a double in C++?

Is there a "standard" way to do this type of things? Or do I have to roll my own function?

Right now I'm doing sth like this:

#include <string>
#include <sstream>



int main() {
    std::string s("1.60000000000000000000000000000000000e+01");
    std::istringstream iss(s);
    double d;
    iss >> d;
    d += 10.303030;
    std::cout << d << std::endl;
}

Thanks!

+3  A: 

You want the standard c function atof ([A]SCII to [F]loat, but it actually uses doubles rather than floats).

Russell Newquist
This will be much faster than using C++ stream objects.
Heath Hunnicutt
atof converts to a double like the OP and the docs says.
luke
@Heath: It's always easy to be fast when you skip important steps: `atof("0.0")` vs. `atof("blah")`. (Note: I'm not trying to defend C++ streams, they _are_ slower than they should be. But they do indicate errors in a unambiguous way.)
sbi
+7  A: 

Something like this? This would be the "C++" way of doing it...

#include <sstream>
using namespace std;

// ...

    string s = "1.60000000000000000000000000000000000e+01";
    istringstream os(s);
    double d;
    os >> d;
    cout << d << endl;

Prints 16.

Thomas
If you've got boost, then `double d = boost::lexical_cast<double>(s)` will do the same thing.
Mike Seymour