In: Computer Science
Write a program that takes its input from a file of number type double and outputs the average of the numbers in the file to the screen. The file contains nothing but numbers of the type double separated by blanks and/ or line breaks. If this is being done as a class assignment, obtain the file name from your instructor.
File name: pr01hw05input.txt
78.0 87.5 98.1 101.0 4.3 17.2
78.0 14.5 29.6 10.2 14.2 60.7
78.3 89.3 29.1 102.3 54.1 67.2
78.6 67.5 92.1 80.0 64.3 37.3
88.0 80.5 49.2 100.0 64.9 67.4
74.5 83.4 99.1 90.4 54.3 67.1
78.1 27.5 19.1 100.5 64.3 67.8
73.7 87.9 94.5 110.1 54.2 57.5
78.0 82.5 89.1 150.7 8.32 69.6
If you have any doubts, please give me comment..
#include<iostream>
#include<fstream>
using namespace std;
int main(){
string filename;
cout<<"Enter input filename: ";
cin>>filename;
ifstream inFile;
inFile.open(filename.c_str());
if(inFile.fail()){
cout<<"Unable to open file"<<endl;
return -1;
}
double num, sum = 0;
int n = 0;
while(inFile>>num){
sum += num;
n++;
}
double avg = sum / n;
cout<<endl<<"Average is: "<<avg<<endl;
return 0;
}