In: Computer Science
One dimensional dynamic array
Write a function that returns the number of integers in an input file stream with the following interface:
int findNumber(ifstream &x);
Then, use this number to dynamically allocate an integer array.
Write another function that reads each number in an input file stream and assign the value to the corresponding array element with the following interface:
void assignNumber(ifstream &x, int y[ ]);
In your main( ), first open “in.dat” as an input file. Next, apply findNumber( ) function on this input stream. Then, you close the file stream. Dynamically allocate a one-dimensional array based on the number of integers in in.dat. After that, you re-open “in.dat” as an input file, and apply assignNumber( ) function on the file stream and assign each array element with the corresponding value in in.dat.
At the end of main( ), print out every element of the dynamically allocated array as an evidence of your work in the format of a screenshot.
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
input file: in.dat
-------
35
12
40
56
10
16
main.cpp
-----
#include <iostream>
#include <fstream>
using namespace std;
int findNumber(ifstream &x);
void assignNumber(ifstream &x, int y[ ]);
int main(){
ifstream infile;
int n;
int *arr;
infile.open("in.dat");
if(infile.fail()){
cout << "ERROR: could not
open file in.dat" << endl;
return 1;
}
n = findNumber(infile);
infile.close();
arr = new int[n];
infile.open("in.dat");
assignNumber(infile, arr);
infile.close();
cout << n << " numbers read from file
are-" << endl;
for(int i = 0; i < n; i++)
cout << arr[i] <<
endl;
delete []arr; //deallocate memory
return 0;
}
int findNumber(ifstream &x){
int count = 0;
int num;
while(x >> num)
count++;
return count;
}
void assignNumber(ifstream &x, int y[ ]){
int i = 0;
int num;
while(x >> num){
y[i++] = num;
}
}
output
----
6 numbers read from file are-
35
12
40
56
10
16