Write a program that merges the numbers in two files and writes all the numbers
ID: 3819954 • Letter: W
Question
Write a program that merges the numbers in two files and writes all the numbers 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 longer 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. Sample output (bolded text denote input from user) Filenames are restricted to 12 characters Enter the first of two input file names HW10F1.txt Now a second input file name HW10F2.txt Enter the output file name. WARNING: ANY EXISTING FILE WITH THIS NAME WILL BE ERASED. output.txt END OF PROGRAM Contents of file HW 10F1.bxt are: 357 10 Contents of file HW10F2.txt are: 1 2 4 68 Contents of merged file, output.txt are: 1 2 3 4 5 67 8 10Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
string name;
cout << "Enter name of first file: ";
cin >> name;
fstream input1(name.c_str(), std::ios_base::in);
cout << "Enter name of second file: ";
cin >> name;
fstream input2(name.c_str(), std::ios_base::in);
cout << "Enter name of output file: ";
cin >> name;
ofstream output;
output.open(name.c_str());
int i , j;
bool file1 = false, file2 = false;
if(input1 >> i) {
file1 = true;
}
if(input2 >> j) {
file2 = true;
}
while (file1 && file2)
{
if(i < j) {
output << i << endl;
if(input1 >> i) {
file1 = true;
} else {
file1 = false;
}
} else {
output << j << endl;
if(input2 >> j) {
file2 = true;
} else {
file2 = false;
}
}
}
if(!file1) {
output << j << endl;
while(input2 >> j) {
output << j << endl;
}
}
if(!file2) {
output << i << endl;
while(input1 >> i) {
output << i << endl;
}
}
return 0;
}
I have kept two files input1 and input2.txt in same directory..
input1.txt:
2
3
6
7
8
input2.txt:
1
4
7
12
output: (in output.txt file)
1
2
3
4
6
7
7
8
12
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.