gpt4 book ai didi

c++ - 迭代 ifstream

转载 作者:行者123 更新时间:2023-12-03 12:50:30 26 4
gpt4 key购买 nike

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

我的问题是:我有一个包含多行数据的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() 来做到这一点,然后将结果字符串拆分为每个“”,但我想知道是否有任何“更干净”的方法可以做到这一点。

最佳答案

是的,在 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<<" ";
}

关于c++ - 迭代 ifstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31894217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com