查询有关在C ++中将数据从字符串转换为浮点数的问题

时间:2015-02-08 05:22:01

标签: c++

我有以下表格的数据:

7630000.0
2150000.0
5.85E7
4810000.0
1.863E8
2023428.2112
3.365126E9

我逐行读取这个数据,并使用C ++函数atof()将字符串转换为浮点数。但是,我发现某些数据项如3.365126E9错误地被atof()转换为18446744071562067968。有人可以建议我应该如何进行适当的转换?

我在ubuntu 12.04上使用C ++与GCC和G ++

1 个答案:

答案 0 :(得分:1)

使用C ++ 11有stod,它是字符串加倍。

以下是使用sstream的简单示例:

#include <iostream>   // std::cout
#include <string>     // std::string, std::stod
#include <sstream>   //std::istring

int main ()
{
    std::string example = "5.85E7";
    std::istringstream   os;
    os.str(example);
    double output;
    os >> output;
    std::cout << output << std::endl;
    return 0;
}

更复杂的方法是:

#include <iostream>   // std::cout
#include <string>     // std::string, std::stod
#include <sstream>   //std::istring

double StringToDouble(const std::string & text){
    std::istringstream   os;
    double output;
    os.str(text);
    os >> output;
    return output;
}    

int main ()
{
    std::string example = "5.85E7";
    std::cout << StringToDouble(example) << std::endl;
    return 0;
}

可以找到更详细的说明here

相关问题