How to properly read from a file using a for loop until end of file?

Hey guys,

I have some code that requires me to read from a file into an array of objects. The array's maximum size is 25 elements. So I need to see some code on how to properly read into the array of objects using a for loop.
It must read from the file until the end of the file is reached or the maximum size is occupied in the array of objects. I have code that does exactly this using a while loop but I have to incorporate the eof() flag and max size of the array using a for loop. I tried some code a while back but I had some difficulty incorporating the eof() flag. It seemed like it kept bypassing it and displayed 25 as the number of objects in the array when using a counter inside of the for loop. Any help will be appreciated!

Thank you,
MisterTams
closed account (48T7M4Gy)
Adapting the sample from here is one possible way to consider
http://www.cplusplus.com/reference/ios/ios/eof/
Hi,

Put the read operation and the size condition both into the while conditional:

1
2
3
4
5
6
7
8
9
10
11
constexpr std::size_t SIZE = 25;

int TheArray[SIZE] = {};

std::size_t NumItemsRead = 0;

while (std::getline (infile,TheArray[NumItemsRead] ) && NumItemsRead < SIZE  ) {
  ++NumItemsRead;
}
if (NumItemsRead < SIZE) {std::cout << "Only " <<  NumItemsRead << "items have been read in\n";}
else {std::cout << "All items read in\n";}


If the std::getline fails( 1 reason might be eof), the while loop will end.

Note that checking for eof , only really works when reading 1 char at a time from the file. That is a C style approach, and is probably not the way to go for modern C++.
Last edited on
Topic archived. No new replies allowed.