c++ - 为什么 std::stol 不能使用科学记数法?

标签 c++

我有这个代码:

#include <iostream>

int main() {
    long l1 = std::stol("4.2e+7");
    long l2 = std::stol("3E+7");
    long l3 = 3E7;
    printf("%d\n%d\n%d\n", 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

关于c++ - 为什么 std::stol 不能使用科学记数法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28696405/

相关文章:

c++ - 模板策略模式

c++ - OS 可移植 C/C++ XML 解析器

c++ - LNK2019 : unresolved external symbol, 在不存在的*.obj文件中搜索

c++ - 返回迭代器与松散耦合

c++ - POSIX C/C++ 日志文件(VEX V5 大脑)

c++ - 将 PySide 对象传递给 C++

C++:我应该捕获所有异常还是让程序崩溃?

c++ - Cin 坚持输入并错误读取

c++ - C++ 中的简单正则表达式用法

c++ - C++中的C复数?