Write a program that takes its input from a file of numbers of type double and outputs the average of the numbers in the file to the screen. The file contains nothing but numbers of type double separated by blanks and/or line breaks.
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
double get_average(ifstream&);
void output_average(double);
const char file_name[15] = "infile.txt";
int main()
{
ifstream inStream;
inStream.open(file_name);
if (inStream.fail())
{
cout << "Input file opening failed. \n";
exit(1);
}
double average = get_average(inStream);
output_average(average);
inStream.close();
return 0;
}
double get_average(ifstream& instream)
{
int index = 0;
double next = 0, sum = 0;
cout << "The numbers from the file are below." << endl;
while (instream >> next)
{
index++;
cout << next << " ";
sum = sum + next;
}
cout << endl;
return (sum/index);
}
void output_average(double average)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "The average of the numbers in the file is \n"
<< average << endl;
}