0

c++ 中是否有一个内置函数可以处理将“2.12e-6”之类的字符串转换为双精度字符串?

4

3 回答 3

7

strtod()

于 2011-01-16T04:11:37.410 回答
3

atof应该做的工作。的输入应该是这样的:

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. 
于 2011-01-16T04:12:49.373 回答
1

如果您更愿意使用 c++ 方法(而不是 ac 函数),
请像所有其他类型一样使用流:

#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 当然有一个方便的捷径 boost::lexical_cast<double> 或者自己编写也很简单。

于 2011-01-16T05:57:25.580 回答