In: Computer Science
Please answer it in C++
The first function should take a reference to an ifstream object and a reference to an array of double, read data into the array from the file and return the number of values read. It should stop reading when the end of the file is reached. The data file contains prices of an unspecified item, one per line.
The second function takes a reference to an array of double, and an int indicating the number of elements in the array and then calculates and returns the average of the values in the array.
(b) The program below is designed to use the functions readData() and findAverage()defined in part a above to read the data from a file called prices.txt to the array and then calculate and display the average. Currently, the program has missing sections indicated by the empty text boxes. Complete the program by inserting the missing statements into the spaces provided.
Code for the following problem:-
#include <iostream>
#include<fstream>
using namespace std;
int readData(ifstream &ptr,double* values)// function to
read data from prices.txt
{double x;
int count=0;
if (!ptr) { //to check if our file is read correctly.
cout << "Unable to open file datafile.txt";
exit(1); // call system to stop
}
while (ptr >> x) {
values[count]=x;
count++;
}
return(count);
}
double findAverage(double* values,int count)// function to fid
average
{double sum=0;
for(int i=0;i<count;i++)
sum+=values[i];
return(sum/count);
}
int main()
{
ifstream inFile;
inFile.open("prices.txt");
double values[1000];
int count=readData(inFile,values);
double average=findAverage(values,count);
cout<<"Average= "<<average;
return 0;
}
Sample input file used :-
10.54
20
45.98
23.55
45.8
Screenshots of IDE:-
SCREENSHOT OF INPUT FILE USED:-
SCREENSHOT OF OUTPUT:-
************************IN CASE OF ANY DOUBT FEEL FREE TO LEAVE A COMMENT***************************