Question

Is there a built in function in c++ that can handle converting a string like "2.12e-6" to a double?

Was it helpful?

Solution

atof should do the job. This how its input should look like:

A valid floating point number for atof is formed by a succession of:

An optional plus or minus sign 
A sequence of digits, optionally containing a decimal-point character 
An optional exponent part, which itself consists on an 'e' or 'E' character followed by an optional sign and a sequence of digits. 

OTHER TIPS

If you would rather use a c++ method (instead of a c function)
Use streams like all other types:

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

int main()
{
    std::string     val = "2.12e-6";
    double          x;

    // convert a string into a double
    std::stringstream sval(val);
    sval >> x;

    // Print the value just to make sure:
    std::cout << x << "\n";

    double y = boost::lexical_cast<double>(val);
    std::cout << y << "\n";
}

boost of course has a convenient short cut boost::lexical_cast<double> Or it is trivial to write your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top