Reputation: 21
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...
any better ideas?
Upvotes: 2
Views: 1954
Reputation: 61910
Use std::vector
:
std::ifstream inFile(fileName);
std::vector<int> ints{
std::istream_iterator<int>(inFile),
std::istream_iterator<int>()
};
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.
Upvotes: 8