Previously, when we read from a file, it was easy to know what we were reading, as we created the file, and knew how many data elements we put into the file. But what if we don’t know? We just know we need to read the whole file and work with that data?
That’s were we can easily use a loop to work with the file.
The input file stream gives us an eof()
method, that lets us see if we’re at the end of a file. We want to keep running while we’re not at the end of a file, therefore we use the Boolean not operator !
and specify !input.eof() which could be read as: While the input file is not at the End of File.
ifstream input("scores.txt");
double sum = 0;
double number;
while(!input.eof())
{
input >> number;
sum += number;
cout >> number >> " ";
}
input.close();
cout << endl << "The sum is: " << sum << endl;
Using C++ While Loops to Read a File was originally found on Access 2 Learn