Question #210185

Write a program to input a list of numbers (type double) from a file and outputs the numbers and the average into another text file. Also show me the output on the screen. The file contains nothing but the numbers of type double separated by blanks and/or line breaks.

Expert's answer

#include <iostream> 
#include <fstream> 


using namespace std; 


int main() 
{ 
	double n; 
	ifstream in;  
	ofstream out; 
	
	in.open("text1.txt");  
	
	if(in.fail( ))
	{ 
		cout << "Error opening input file"<<endl; 
		return 1;
	}
	
	out.open("text2.txt"); 
	
	if(out.fail( )) 
	{	
		cout << "Error opening output file"<<endl; 
		return 0; 
	} 


	double sum=0;
	int count=0;


	while(!in.eof())
	{
		in>>n;
		sum=sum+n;
		count++;
	}


	double avg=0;


	avg=sum/double (count); 
	cout<<"sum "<<sum<<" count "<<count<<" average "<<avg;
	out<<avg;
	
	in.close();	 
	out.close(); 
	
	return 0;


}
LATEST TUTORIALS
APPROVED BY CLIENTS