C++ 从文件到浮动的文本

C++ 从文件到浮动的文本,c++,string,floating-point,C++,String,Floating Point,我有std::vector 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. 如何将这些字符串转换为浮点变量? 当我尝试时: scanf(WorldData[i].c_str(), "%f %f %f %f %f", &x, &y, &z, &tX, &tY);

我有std::vector 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.
如何将这些字符串转换为浮点变量? 当我尝试时:

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);
变量x、y、z、tX、tY会得到一些奇怪的数字。

使用:


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

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;
}
然后,您可以使用istream_迭代器创建坐标向量:


你真的用过scanf吗?如果你在读字符串,你应该使用sscanf.omg我还没有看到,我想是时候睡觉了:P多谢了,应该是std::istringstream iss;iss.rdbuf->pubsetbufWorldData[i].c_str,WorldData[i].大小;如果您希望避免WorldData[i]中不必要的数据重复。
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;
}
std::ifstream in("world.txt");

// initialize vector of coords from file:
std::vector<coord> coords((std::istream_iterator<coord>(in)),
                           std::istream_iterator<coord>());