c++ - 从文件到 float 的文本

标签 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.

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

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

最佳答案

我不是从文件读入 vector ,然后从 vector 读入坐标,而是直接从文件读入坐标:

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 创建一个坐标 vector :

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

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

关于c++ - 从文件到 float 的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391981/

相关文章:

c++ - 我应该如何计算 'binary' 矩阵中唯一行的数量?

C++ 异常处理和内存的动态分配

Powershell 中的 RegEx,合并替换调用

java - 恢复 Java 中 string.split() 分割的字符串

c++ - 如何在不越过缓冲区的情况下将字符串复制到 C++ 中的 char 数组中

c# - 在 .Net 运行时为测试用例散列 float

floating-point - sybase 15.7 float 到数字舍入错误

C++ 音频转换(mp3 -> ogg)问题

c++ - 如何通过按位运算在 double 之间执行求和

c++ - Cuda 内核返回 vector