Iterate over ifstream

Iterate over ifstream

本文关键字:ifstream over Iterate      更新时间:2023-10-16

我知道已经有很多关于如何迭代ifstreams的答案,但是没有一个真正帮助我找到解决方案。

我的问题是:我有一个包含多行数据的txt文件。txt文件的第一行告诉我其余的数据是如何组成的。例如这是我的TXT文件:

5 5 5
0.5 0.5 0.5
0 0 0
0 0 1
0 0 -1
0.5 1 0
0 0 -1 0
0 0 1 1
0 -1 0 1
1 0 0 3
0 1 0 1
...

这应该告诉我的程序执行

double a,b,c
inf >> a >> b >> c

为前5行

double a,b,c,d
inf >> a >> b >> c >> d

表示接下来的5行等

我想我可能能够通过使用getLine(),然后在每个"上分割结果字符串来做到这一点,但我想知道是否有任何"更干净"的方式来做到这一点。

yes在while循环中使用getline,并使用istringstream和istream_iterator解析数据,并将单个数据保存在vector中。

int main()
{
 std::ifstream infile(<absolute path to file>);
 std::string input="0 0 -1 0";
 std::vector<std::vector<float>> data;
 while( getline(infile,input))
 {
    std::istringstream iss(input);
    std::vector<float> input_data{istream_iterator<float>{iss},
                      istream_iterator<float>{}};
    data.push_back(input_data);   
}
for( const auto & x: input_data)
  std::cout<<x<<" ";
}

为什么不循环呢?

for(int i = 0; i < 5; i++) {
    double a,b,c;
    inf >> a >> b >> c;
    // Do something with a,b,c
}
for(int i = 0; i < 5; i++) {
    double a,b,c,d;
    inf >> a >> b >> c >> d;
    // Do something with a,b,c,d
}