C++ Write a C++ program that merges the numbers in two files and writes all the
ID: 653728 • Letter: C
Question
C++
Write a C++ program that merges the numbers in two files and writes all the numbers into a third file.
Each input file contains a list of integers in order from smallest to largest.
After the program is run, the output file will contain all the numbers from both input files in order from smallest to largest.
Your program should define a function that is called with three arguments; the two input-file streams and the output-file stream.
You should not read in all the numbers, sort them and then write them to the output file.
Read one number from each input file and decide which of them should be written into the output file.
Then replace that number with the next value in that input file.
You should prompt the user to enter the names of the two input files and the output file.
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int num1, num2;
ifstream inputFile;
ifstream inputFile2;
inputFile.open ("input1.txt");
inputFile2.open("input2.txt");
ofstream outputFile;
outputFile.open("output.txt");
inputFile >> num1;
inputFile2 >> num2;
while(inputFile.eof() && inputFile2.eof())
{
if (num1 < num2)
{
outputFile << num1;
inputFile >> num1;
}
else
{
outputFile << num2;
inputFile2 >> num2;
}
}
inputFile.close();
inputFile2.close();
outputFile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.