(a) Write a function in C++ called readNumbers() to read data into an array from a file. Function should have the following parameters:
(1) a reference to an ifstream object
(2) the number of rows in the file
(3) a pointer to an array of doubles
The function returns the number of values read into the array. It stops reading if it encounters a negative number or if the number of rows is exceeded.
(b) Write a program with the main() function is designed to use the readNumbers() function from the previous part of this question to read the data from a file called inputData.txt to the array.
The following C++ program does all the required tasks:(Read the comments). The number of rows to be read from the file is passed to the function.
#include <iostream>
#include <fstream>
using namespace std;
//The required function
int read_numbers(ifstream &f, int r, double *p) {
int i=0;
//To read each double
double x=0.0;
while(i<r) {
//if the file exhausts
if(!(f >> x)) break;
//for negative numbers
if(x<0) break;
//read the number into array
p[i] = x;
//increment i
i++;
}
return i;
}
int main()
{
ifstream f1;
f1.open("inputData.txt");
//rows to be read from the file
// this can be calculated as well from the file
int rows = 6;
double p[rows];
int nums = read_numbers(f1, rows, p);
cout << nums << endl;
f1.close();
}
Create an input file -- inputData.txt (in the same folder as the above cpp program)
3.5
4.7
6
56
-1
76
Output:
4
As 4 lines are read successfully into the array. The 5th line contains a negative number and the loop breaks at this line.
Note(Optional):- The number of lines in the file can also be precalculated in main() if required:
double x=0.0;
int rows = 0;
while(f1>>x) rows++;
//but then clear the state and move f1 again to the start of the file
f1.clear();
f1.seekg(0);
Get Answers For Free
Most questions answered within 1 hours.