Using C++ You are given two files “HW6Prob2a.dat” and “HW6Prob2b.dat” with numbe
ID: 3808923 • Letter: U
Question
Using C++
You are given two files “HW6Prob2a.dat” and “HW6Prob2b.dat” with numbers in them. One file MAY have more numbers than the other. Write a program to read the numbers from two files and find the sum of the number. Store the sum in the third file “Results.txt”. Make sure to check if the files have been properly opened. For example, if the first number of 1030Prob2a.txt is 10 and the first number of 1030Prob2a.txt is 20, the sum is 30 and hence the first number stored in Results.txt is 30. If the first number of 1030Prob2a.txt is 10 and the first number of 1030Prob2a.txt is 15, the sum is 25 and hence the first number stored in Results.txt is 25. Since one file MAY BE shorter than the other, all numbers from the longer file will not have a peer in the shorter file to add to. In that case, just add zero to the numbers of the longer file. Your program cannot assume to know which file is longer or shorter beforehand. They may also be of equal size. The program must be generic to work for files of all sizes. HINT: 1. Start reading both files in a loop, one number at a time from each file, and sum them and store in the result file. 2. Use two Boolean variables to track whether the files have ended, and use these Booleans in your loop. Remember streaming operations return a Boolean. So, you can use a statement such as bool my_bool=(infile>>my_var); 3. Once the shorter file ends, stop the loop. 4. Keep on reading the longer file in a separate loop, add zero to what you read and store the sum in the result file HW6Prob2a.dat: 10.23 -36.527 26.4544 11.25 63.112 -0.25 22.369 21.223 34.501 -17.201 94.227 -10.375 22.369 17.44 HW6Prob2b.dat 17.36 16.362 11.25 71.362 -11.75 28.47 43.26 18.231 11.305 -15.129 16.54
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin1, fin2;
ofstream fout;
fin1.open("HW6Prob2a.dat");
fin2.open("HW6Prob2b.dat");
fout.open("Results.txt");
double score1, score2, total;
while(!fin1.eof() && !fin2.eof())
{
fin1 >> score1;
fin2 >> score2;
total = score1 + score2;
fout << total << endl;
}
while(!fin1.eof())
{
fin1 >> score1;
fout << score1 << endl;
}
while(!fin2.eof())
{
fin2 >> score2;
fout << score2 << endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.