2015-02-24 30 views
1

我有這樣的代碼:爲什麼std :: stol不能用科學記數法工作?

#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考慮到科學記數法?

回答

1

您正在尋找的功能是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