c ++中是否有内置函数可以处理像“2.12e-6”这样的字符串转换为double?
答案 0 :(得分:7)
答案 1 :(得分:3)
atof
应该做的工作。 This其输入应如何显示:
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.
答案 2 :(得分:1)
如果您更愿意使用c ++方法(而不是c函数) 像所有其他类型一样使用流:
#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";
}
提升当然有一个方便的捷径提升:: lexical_cast&lt; double&gt;或者编写自己的文章是微不足道的。