Iterate over ifstream
Iterate over ifstream
我知道已经有很多关于如何迭代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
}
相关文章:
- ifstream什么都没读
- ifstream文件在从行中读取时被清除
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 将 ifstream 拆分为 n 个流?
- 如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?
- 我在 ifstream input_file(文件名)行中收到错误"no matching function to call";
- 尝试打开 ifstream 时出现"Incomplete type"错误
- 是否可以在没有真实文件的情况下创建 ifstream
- 虽然循环不读取整个 ifstream 文件
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- Ofstream和IFSTREAM有什么区别?
- 如何将QByteArray转换为std::istream或std::ifstream?
- ifstream 跳过数字,只写 0
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 在函数中声明的 ifStream 对象在发布模式下不起作用
- fstream / ifstream / ofstream 对象如何转换为布尔值
- ifstream 尝试读取 9 到 13 之间的无符号字符时非常奇怪的行为
- 尝试在 C++ 中为 ifstream 提供一个变量
- ifstream 读取的字符与文件中写入的字符不同
- Iterate over ifstream