Ok, you wanted step by step, so I'll go line by line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
// Creates two variables of type int - positive or negative whole numbers
int number, count = 0;
// I believe there is an error here with the comma
// Should create a variable of double precision floating point (a decimal)
double, sum = 0;
// Reads an integer from the fileName object and stores it in number
fileName >> number;
// Takes the sum and sets it equal to the new number and the old sum
sum = sum + number;
// Increments count (the variable that tells you how many numbers there are
count++;
// The start of a while loop
// Checks to make sure the end of file hasn't been reached on the fileName object
while (!fileName.eof())
{
// Reads another number into the variable number from fileName
fileName >> number;
// Adds the sum and number together again and assigns it to sum
sum = sum + number;
// Increases the count
count++;
}
// The while loop will continue as long as there are more numbers
// Displays "Average = " and then the value of sum divided by count
// Since sum was a double, it will return a value with double precision
// The displays an end of line character/carriage return (depends on your OS)
cout << "Average = " << sum/count << endl;
// Displays another EOL/CR character
cout << endl;
// Closes the file
fileName.close();
|
There is a few errors in function itself, I'm guessing either failed copy of it or whatever. It can also be shortened up a little using some of the simple shortcuts of C++ such as the
+=
operator which adds whatever is on the right to whatever is on the left and assigns it to the left variable. A do/while loop would also work a little better in this situation. And if for whatever reason there is no values in the file, you'll get a runtime error, I believe, since you'd be dividing by 0.
But how does it get to the next line of the file and, eventually, to the bottom/end? |
This, my friend, is some of the magic of the fstream objects. It moves how you tell it to, even if you don't know you're doing such a thing. By default, the fstream object ignores whitespace, spaces, line returns, etc. and only reads out what it is told to, in this case, an int.
When it reaches the end of a file, it sets a flag. The while loop is checking that flag on each loop by calling
fileName.eof()
. If the EOF is reached, the function will return true. Since the while statement has a !, not equal to, as long as .eof() is false, it will continue to run. Once it's true, it will break the loop.