Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

double* read_file(int& size, ifstream& infile); This function reads data from in

ID: 3684532 • Letter: D

Question

double* read_file(int& size, ifstream& infile);

This function reads data from infile, and sets the size reference parameter to the number of scores read from the file. It returns a pointer to an array on the heap. That array should have exactly size elements. Of course, you won’t know ahead of time how many scores in the input file until you reach the end of file. Start with an array of CAPACITY elements (where CAPACITY is a constant integer and CAPACITY = 3), and double the size whenever the array fills up. Be sure to delete any intermediate arrays

Please help! I dont understand pointer variables

Explanation / Answer

Here is the code for you:

#include <iostream>
#include <fstream>
using namespace std;

double* read_file(int& size, ifstream& infile);
int main()
{
ifstream inputFile;
string fileName;
cout<<"Enter the name of the file to read the scores: ";
cin>>fileName;
inputFile.open(fileName);
int size = 0;
double *array = read_file(size, inputFile);
for(int i = 0; i < size; i++)
cout<<*(array + i)<<" ";
cout<<endl;
}
double* read_file(int &size, ifstream& infile)
{
const int CAPACITY = 3;
double* arr = (double *)malloc(sizeof(double)*CAPACITY);
size = CAPACITY;
int count = 0;
while(!infile.eof())
{
infile>>arr[count];
count++;
if(count == size)
{
double * arr = (double *) realloc(arr, size * 2);
size *= 2;
}
}
double *finalArray = (double *) realloc(arr, count);
//delete [] arr;
size = count;
return finalArray;
}