0

我有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.

我如何将这些字符串转换为浮点变量?当我尝试时:

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 得到一些奇怪的数字。

4

2 回答 2

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;
}

然后,您可以使用以下方法创建坐标向量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>());
于 2012-05-01T00:00:40.293 回答
3

使用sstream

std::istringstream iss(WorldData[i]);
iss >> x >> y >> z >> tX >> tY;
于 2012-04-30T23:54:12.373 回答