迭代ifstream

时间:2015-08-08 14:41:46

标签: c++

我知道有很多关于如何迭代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()然后将结果字符串拆分为每个“”来做到这一点,但我想知道是否有任何“更清洁”的方法。

2 个答案:

答案 0 :(得分:0)

为什么不循环?

new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|");

答案 1 :(得分:0)

是在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<<" ";
}
相关问题