为什么std::stol不适用于科学记数法

Why does std::stol not work with scientific notation?

本文关键字:适用于 std stol 不适用 为什么      更新时间:2023-10-16

我有这个代码:

#include <iostream>
int main() {
    long l1 = std::stol("4.2e+7");
    long l2 = std::stol("3E+7");
    long l3 = 3E7;
    printf("%dn%dn%dn", l1, l2, l3);
    return 0;
}

预期输出42000000, 3000000, 3000000但实际输出为(在 ideone C++14 和 VS2013 上测试(:

4
3
30000000

为什么会这样,无论如何都要让std::stol考虑到科学记数法?

您要查找的函数是std::stof而不是std::stolstd::stof在引擎盖下调用std::strtod,它支持科学计数法。但是,std::stol在引擎盖下称std::strtol,但事实并非如此。

#include <iostream>
#include <string>
int main() {
    long l1 = std::stof("4.2e+7");
    long l2 = std::stof("3E+7");
    long l3 = 3E7;
    std::cout << l1 << "n" << l2 << "n" << l3;
    return 0;
}

输出:

42000000
30000000
30000000

仅供参考,对于其他偶然发现此解决方案的人来说,在包含指数的科学记数法数字的字符串中读取的更强大的方法是使用 std::stringstream ,如 C++ 食谱和此 StackOverflow 问题("使用 stringstream 浮点的字符串"(中所述

实际上,像这样:

#include <sstream>
#include <string>
   std::string number = "1.0E+6";
   std::stringstream ss(str);
   double d = 0;
   ss >> d; // d = 1.0E6
相关文章: