Is there a built in function in c++ that can handle converting a string like "2.12e-6" to a double?
Asked
Active
Viewed 3,111 times
0
-
what do yo mean by "built in"? In the standard run-time library? – ThomasMcLeod Jan 16 '11 at 04:12
-
2You tagged the question `atof` -- is there some reason you believe `atof` is not the correct function? – Gabe Jan 16 '11 at 04:15
3 Answers
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
-
-
@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
-