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

Soa*_*apy 2 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;
}
Run Code Online (Sandbox Code Playgroud)

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

4
3
30000000
Run Code Online (Sandbox Code Playgroud)

为什么会这样?有没有办法std::stol考虑科学记数法?

小智 5

您正在寻找的功能是std::stof而不是std::stol。在后台std::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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

42000000
30000000
30000000
Run Code Online (Sandbox Code Playgroud)