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.

これらの文字列を float 変数に変換するにはどうすればよいですか? 私が試したとき:

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 に答える