Ian Burris
Ian Burris

Reputation: 6515

Converting a string like "2.12e-6" to a double

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

Upvotes: 0

Views: 3132

Answers (3)

Loki Astari
Loki Astari

Reputation: 264391

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.

Upvotes: 1

341008
341008

Reputation: 10232

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. 

Upvotes: 3

Martin Beckett
Martin Beckett

Reputation: 96109

strtod()

Upvotes: 7

Related Questions