This program consists of two parts. In part one, you will read from TWO input fi
ID: 3688627 • 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
for part1:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile1,infile2;
int num,x;
x=0;
double aver,total=0.0;
//part1
infile1.open("D:input1.txt");
infile2.open("D:input2.txt");
while(!infile1.eof())
{
infile1>>num;
total=total+num;
x++;
}
while(!infile2.eof())
{
infile2>>num;
total=total+num;
x++;
}
aver=total/x;
cout<<aver<<' ';
infile1.close();
infile2.close();
return 0;
}
Similarly for part 2 you can write:
ofstream outfile1,outfile2;
infile1.open("D:input1.txt");
infile2.open("D:input2.txt");
outfile1.open("D:output1.txt");
outfile2.open("D:output2.txt");
while(!infile1.eof()){
infile1>>num;
if(num<aver)
outfile1 << num << endl;
else
outfile2 << num << endl;
}
while(!infile2.eof()){
infile2>>num;
if(num<aver)
outfile1 << num << endl;
else
outfile2 << num << endl;}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.