I need the following question answered in c++. Need help. Thank you. \"Write a p
ID: 3729318 • Letter: I
Question
I need the following question answered in c++. Need help. Thank you.
"Write a program that merges the numbers in two files and writes all the numbers into a third file. Your program takes input from two different files and writes its output into a third file. Each input file contains a list of numbers of type "int" in sorted order from the smallest to the largest. After the program is run, the output file will contain all the numbers in the two input files in one long list in sorted order from smallest to largest. Your program should define a function that is called with the two input-file streams and the output file stream as three arguments."
Please show that the program runs. Thank you again.
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
void merge(string file1, string file2, string output)
{
int num1, num2;
ifstream inputFile;
ifstream inputFile2;
inputFile.open (file1);
inputFile2.open(file2);
ofstream outputFile;
outputFile.open(output);
inputFile >> num1;
inputFile2 >> num2;
while(!inputFile.eof() && !inputFile2.eof())
{
if (num1 < num2)
{
outputFile << num1<<" ";
inputFile >> num1;
}
else
{
outputFile << num2<<" ";
inputFile2 >> num2;
}
}
while(!inputFile.eof()){
inputFile >> num1;
outputFile << num1<<" ";
}
while(!inputFile2.eof()){
inputFile2 >> num2;
outputFile << num2<<" ";
}
inputFile.close();
inputFile2.close();
outputFile.close();
}
int main() {
merge("input1.txt", "input2.txt", "output.txt");
cout<<"file successfully merged"<<endl;
return 0;
}
input1.txt
1 2 3 4 4 5 6 7 7 7 8 9 10 20
input2.txt
11 12 13 14 14 15 15 15 16 17 18 19 20
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.