# C++ File Question

• 10-25-2011
iGuardian
C++ File Question
In this program I have to write a program that has to take the inputs of a file and output the average of the sum of numbers. My question is regarding how to average the numbers by adding the total numbers in the file. Would I have to do a count?

Code:

```#include <fstream>#include <iostream> int main() {     using namespace std;     ifstream in_stream;     cout << "I am going to take the numbers from the input file and average them." << endl;     in_stream.open ( "input.dat" );     if ( in_stream.fail( ) )     {         cout << "Please check if the file is saved properly. It could not open." << endl;     }     double first_number, next_number, total_numbers;     int count = 0;     in_stream >> first_number >> next_number >> total_numbers;     first_number = 0;     next_number = first_number + next_number;     cout << "The average of the numbers is ";     cout << ( first_number + next_number ) / total_numbers << endl;     in_stream.close ();     cout << "The program will now close." << endl; }```
• 10-26-2011
cnewbie1
Not sure what you mean? Do you mean how to calculate the average? Then the answer is to add up all numbers and devide it by the number of numbers. F.ex.: The average og 4,5,6 = (4+5+6)/3.

Other than that, it'd depend on how the file is formatted.
• 10-26-2011
GReaper
You need a loop to keep reading numbers until there's nothing else to read. Since for the average you need the sum and the amount, in each iteration add the retrieved number to a sum buffer and increment a counter. When the loop ends, you know what to do.
Just a sample:
Code:

```double temp, sum = 0; int i = 0; while (inputFile >> temp) {     sum += temp;     ++i; }```
• 10-27-2011
iGuardian
Ok, That makes sense, I was once again making it harder than it should have been. When dealing with files do you suggest I only declare one variable rather than declaring many as I did before.
• 10-27-2011
Elysia
Many variables make a program needlessly hard to understand. Don't declare more than needed.