将像“2.12e-6”这样的字符串转换为“2.12e-6”到双

发布于 2024-10-12 12:54:07 字数 45 浏览 2 评论 0原文

C++ 中是否有内置函数可以处理将“2.12e-6”等字符串转换为双精度型?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜是你 2024-10-19 12:54:07

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. 

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. 
沧笙踏歌 2024-10-19 12:54:07

如果您更愿意使用 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;或者自己写也很简单。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文