Problem:
Write a program which reads a stream of integers from a file and stores them in an array. The array is then analyzed to compute the average of all the values in the array and all of the values that are above the average should be printed out to the screen. Specifically, you must write three functions: main, read_into_array, and print_above_average.
main gets the name of the input file from the user and opens the file. read_into_array is then called to read values from the file and store them in the array. It must be passed at least three arguments: the opened file stream, the array, and the total number of slots in the array. You can assume that there will be a maximum of 100 values in the input file and size your array appropriately.
Finally, print_above_average should be called to read through the array, compute the average, and print out all values in the array that are above the average. print_above_average should take two arguments: the array and the actual number of values in the array. Note that this second argument is not the total number of elements that the array can hold, but is instead the number of values read from the file. For example, the array should be able to hold a minimum of 100 values, but there might have only been 15 values in the file.
I'm almost done with the program but I'm having some trouble figuring out the last part which is the print_above_avg. The avg isn't coming out correctly
Thank You!!
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void read_into_array(ifstream& input, int vals[], int size);
void print_above_avg(int vals[], int size);
int main()
{
int vals[100];
ifstream input;
string inf;
cout << "Enter the input file name that you want to analyze: ";
cin >> inf;
input.open(inf.c_str());
if(input.fail())
{
cout << "File couldn't open" << endl;
exit(1);
}
read_into_array(input, vals, 100);
print_above_avg(vals, 100);
return 0;
}
void read_into_array(ifstream& input, int vals[], int size)
{
int val, sum=0 ,i=0;
while(input >> val)
{
vals[i] = val;
i++;
}
}
void print_above_avg(int vals[], int size)
{
int sum=0;
double avg=0;
for(int i=0; i<vals[i]; i++)
{
sum += vals[i];
cout << vals[i] << endl;
avg = sum / vals[i];
}
cout << "The total is " << sum << endl;
cout << "The avg is " << avg << endl;
}