我有一个看起来像这样的文件:
1.23 2.34 4.4 6.5 3.4
3.43 5.34 5.44 4.5 1.4
.... and so on
所以有很多行是用空格划分的。实际上我正在阅读它们:
double values[5];
while (infile >> values[0] >> values[1] >> values[2] >> values[3] >> values4]) {
for (int j = 0; j < 5; j++) {
coordinates.at(x).values.push_back(values[j]);
}
x++;
}
我希望能够将文件中的值数量从 5 更改为 20。有什么快速的方法可以做到这一点吗?我所发现的只是将整行作为一个字符串读取,然后创建一个流并使用大量函数来获取这些值。 我知道我的解决方案也是错误的,因为首先我将它们存储在表中以便稍后将它们放入 vector 中。
更新:
这道题答错了,我自己整理了一下:
string line;
while (getline(file, line)) {
stringstream ss(line);
double val;
while (ss >> val) {
//do something
}
x++;
}
最佳答案
#include <iostream>
#include <fstream>
#include <sstream>
int main() {
std::ifstream file("data");
while (file) {
std::string line;
std::getline(file, line);
std::stringstream ss(line);
while (ss) {
double val;
if (ss >> val) {
//
// do whatever you want here
//
}
}
}
}
关于c++ - 从文件中读取不同数量的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817702/