0

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

Ian Burris
  • 6,325
  • 21
  • 59
  • 80

3 Answers3

7

strtod()

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
3

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. 
341008
  • 9,862
  • 11
  • 52
  • 84
1

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.

Martin York
  • 257,169
  • 86
  • 333
  • 562
  • Effective method, but he did say built in. – Charles Ray Jan 16 '11 at 06:05
  • @Charles: That's why boost::lexical_cast<> is last (as an alternative (as it should be practically builtin as working without it is like stone knoves)). The standard stream stuff is built in though and writting your own version of lexical_cast<> is childs play. – Martin York Jan 16 '11 at 06:12
  • What does "like stone knoves" mean? Is it some British idiom? – Gabe Jan 16 '11 at 07:17