In: Computer Science
Please solve questions in C++ ASAP!! thank you
(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 integers
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.
FUNCTION readNumbers() and C++ CODE with ifstream() as refrence :
//C++ CODE reads data from a text file into an array.
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
//To store elements
vector<int> numbers;
//Function to read Array from file
void readNumbers(ifstream& inputFile){
// Check if exists and then open the file.
if (inputFile.good()) {
// Push items into a vector
int current_number = 0;
//Checking if number in file is positive and number exist
while (inputFile >> current_number and current_number>=0){
numbers.push_back(current_number);
}
// Close the file.
inputFile.close();
// Display the count of numbers read.
cout << "The count of numbers are: ";
cout<<numbers.size();
cout << endl;
}else {
cout << "Error!"; //If error occurs or file is missing.
}
}
int main()
{
ifstream inputFile("inputData.txt");
readNumbers(inputFile);
return 0;
}
INPUT FILE :
OUTPUT :