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

This program consists of two parts. In part one, you will read from TWO input fi

ID: 3688814 • Letter: T

Question

This program consists of two parts. In part one, you will read from TWO input files: "inFile1.txt” and "inFile2.txt” then calculate and display to screen the average of all the numbers read from both files. Before proceeding with the next part you need to close all input files to be able to re-read from them for the next part. In part two, your program should re-open the TWO input files and create (new) TWO output files: "outFile1.txt” and "outFile2.txt”. The program will starts reading from inFile1.txt and write to outFile1.txt the numbers (each on a separate line) that are less than the average AND also write to outFile2.txt the numbers (each on a separate line) that are greater than the average. Perform the same task for the second input file. Make sure to close all input and output files before exiting your program. Test your program using the following: //inFile1.txt 10 39 22 44 12 //inFile2.txt 24 56 32 56 21

Explanation / Answer

/** C++ code to read write and find average */

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <vector>
using namespace std;

double average (vector<int> &a , int n) // function to calculate average
{
double sum = 0;
for (int j = 0; j < n; j++)
{
sum = sum + a[j];
}

sum = sum /n;
return sum;
}


int main()
{
vector<int> v1;
ifstream file1("inFile1.txt"); // opening inFile1.txt
ifstream file2("inFile2.txt"); // opening inFile2.txt

int number;

while(file1 >> number) v1.push_back(number);
while(file2 >> number) v1.push_back(number);

file1.close(); // closing input files
file2.close();

double average1 = average ( v1, v1.size()); // calling the function
cout << "Average of numbers in both files is: " << average1 << endl;


ifstream file5("inFile1.txt"); // opening files again
ifstream file6("inFile2.txt");   
ofstream file3("outFile1.txt"); // opening ouputfiles
ofstream file4("outFile2.txt");

file3 << "Numbers greater than average from both files" <<endl;
file4 << "Numbers less than average from both files" << endl;

while(file5 >> number)
{
cout << number << endl;
if(number > average1) file3 << number << endl;
else file4 << number << endl;
}

while(file6 >> number)
{
if(number < average1) file4 << number << endl;
else file3 << number << endl;
}


  
file5.close(); // closing all opened files
file6.close();
file3.close();
file4.close();

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote