# C++ average of numbers from file



## racketmaster

Hello, I've been reading on how to access files and bring them into your program and print them on the screen and such things like that. I have also figured out how to write directly from the program to a file. However, I have not quite figured out how to work with the numbers from a file. Can someone please show me the source code for: having a txt file with 10 numbers, then with the program calculate the average of those numbers, and then print that average on a new txt file. i'm sure this is an extremely easy thing to do, so can someone please show me the source code for this?

Thank you!


----------



## mgoldb2

PHP:


#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
	int n; 
	ifstream Input;  
	ofstream Output; 
	
	Input.open("num.txt");  
	
	if(Input.fail( ))
	{ 
		cout << "error opening input file"<<endl; 
		return 1;
	}
	
	Output.open("average.txt"); 
	
	if(Output.fail( )) 
	{	
		cout << "error opening output file"<<endl; 
		return 0; 
	} 

	 
	int total=0;
	int count=0;

	while(!Input.eof())
	{
		Input>>n;
		total=total+n;
		count++;
	}

	float average=0;

	average=float(total)/float(count); 
	cout<<"sum "<<total<<" count "<<count<<" average "<<average;
	Output<<average;
	
	Input.close();	 
	Output.close(); 
	
	return 0;

}

This will find the average of all the numbers in the file num.txt and put the result in average.txt.


----------

