从文件到浮动的文本

fex*_*fex 0 c++ string floating-point

我有std::vector<std::string> WorldData.它包含我的文件的每一行,名为world.txt(有opengl 3d协调),它看起来像:

-3.0 0.0 -3.0 0.0 6.0
-3.0 0.0 3.0 0.0 0.0
3.0 0.0 3.0 6.0 0.0 etc.
Run Code Online (Sandbox Code Playgroud)

我怎么能将这些字符串转换为浮点变量?当我尝试:

scanf(WorldData[i].c_str(), "%f %f %f %f %f", &x, &y, &z, &tX, &tY);
or
scanf(WorldData[i].c_str(), "%f %f %f %f %f\n", &x, &y, &z, &tX, &tY);
Run Code Online (Sandbox Code Playgroud)

变量x,y,z,tX,tY得到一些奇怪的数字.

Jer*_*fin 9

而不是从文件读入矢量,然后从矢量到坐标,我直接从文件中读取坐标:

struct coord { 
    double x, y, z, tX, tY;
};

std::istream &operator>>(std::istream &is, coord &c) { 
    return is >> c.x >> c.y >> c.z >> c.tX >> c.tY;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下方法创建坐标向量istream_iterator:

std::ifstream in("world.txt");

// initialize vector of coords from file:
std::vector<coord> coords((std::istream_iterator<coord>(in)),
                           std::istream_iterator<coord>());
Run Code Online (Sandbox Code Playgroud)