开发者

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

Is there a built in function in c++ that can handle conve开发者_运维知识库rting a string like "2.12e-6" to a double?


strtod()


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. 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜