将子字符串从输入文件转换为double值?

时间:2015-10-19 02:28:49

标签: c++ c++11

void getBaseCoord(string droneInfo, double& x, double& y, double& z){
   // x= stod(droneInfo.substr(31, 3));
    //y= stod(droneInfo.substr(34, 3));
   // z= stod(droneInfo.substr(37, 3));
    string strx, stry, strz;
    strx = droneInfo.substr(31, 3);
    stry = droneInfo.substr(34, 3);
    strz = droneInfo.substr(37,3);
    x = stof(strx);
    y = stof(stry);
    z = stof(strz);

以上是我目前正在为新手c ++课程开展的项目的摘录。我正在从输入文件中读取此字符串:

9673767892DroaninAlong4880021DO4.37.33.88.19.33.8U

注释掉的部分是为了函数操作的目的,尝试将字符串行中的子字符串转换为double值。但是,我无法以这种方式转换它们,并且在编译时出现错误,说stod未声明(我猜它认为它是变量?)

在函数中将子字符串转换为double值的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

不确定stod()是什么,但它强烈暗示C library strtod()完全执行该操作。

请注意,该函数有两个参数,但第二个参数可能为NULL。第一个参数是C风格的字符串,因此可能需要进行转换:

void getBaseCoord(string droneInfo, double& x, double& y, double& z)
{
    x = strtod(droneInfo.substr(31, 3).cstr(), NULL);
    y = strtod(droneInfo.substr(34, 3).cstr(), NULL);
    z = strtod(droneInfo.substr(37, 3).cstr(), NULL);
}

答案 1 :(得分:0)

或者,您可以使用select column1, column2, column3 from ... inner join ... order by ..... fetch offset etc 类。你可以这样使用它:

stringstream

如果要重复使用,请记住为此解决方案添加std::string strx = droneInfo.substr(31, 3); double x; std::stringstream ss; ss << strx; ss >> x; 以及{string}对象#include <sstream>。您可以看到完整示例here

相关问题