从文件中读取未知长度的int数组 [英] read int array of unknown length from file
问题描述
如何阅读整数不知其长度,从一个文件一个数组?
我没有看到一个方法来获取数组的大小,所以我尝试了一些临时串-的东西,
但我的code爆炸...
How to read an array of integers with unknown length from a file? I don't see a way to get the size of the array, so I tried some temporary-string-stuff, but my code explodes...
更好的想法?
推荐答案
使用的std ::矢量
:
std::ifstream inFile(fileName);
std::vector<int> ints{
std::istream_iterator<int>(inFile),
std::istream_iterator<int>()
};
的std ::矢量
提供动态存储,所以它会调整为所需,以适应它所持有。我所要做的就是利用这需要一对迭代器,并通过他们循环,开始到结束,并复制值到载体构造。我使用的是会从文件中读取整数,直到一不可,因为是到达文件结尾时的情况下的迭代器。我也用统一的初始化,以避免最令人头痛的解析,采用这种形式的构造函数时容易犯的错误。
std::vector
provides dynamic storage, so it resizes as needed to fit what it holds. All I do is utilize the constructor that takes a pair of iterators and loops through them, beginning to end, and copies the values into the vector. The iterators I'm using will read integers from the file until one can't, as is the case when the end of file is reached. I also use uniform initialization to avoid the most vexing parse, an easy mistake to make when using this form of the constructor.
这篇关于从文件中读取未知长度的int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!