Specifications write a program that merges the integer numbers in two sorted fil
ID: 3936839 • Letter: S
Question
Specifications write a program that merges the integer numbers in two sorted files and writes all the numbers into a third file. Your program should prompt the user for the names of the two input files and the name of the output file. 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 two input file streams and the output file stream as three arguments. Sample Input /Output Enter name for input file-1: input1.txt Enter name for input file-2: input2. Txt Enter name of output file: result.txt input 1.txt input 2.txt result tot 15Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void sortTwoFiles(ifstream& in1, ifstream& in2, ofstream& out);
int main()
{
ifstream iFile1;
ifstream iFile2;
ofstream oFile;
string iFileName1;
string iFileName2;
string oFileName;
cout << "Enter the first input file: ";
cin >> iFileName1;
cout << "Enter the second input file: ";
cin >> iFileName2;
cout << "Enter the output file: ";
cin >> oFileName;
iFile1.open(iFileName1);
if(iFile1.fail())
{
cout << iFileName1 << " file is not opened!" << endl;
system("pause");
exit(1);
}
iFile2.open(iFileName2);
if(iFile2.fail())
{
cout << iFileName2 << " file is not opened!" << endl;
system("pause");
exit(1);
}
oFile.open(oFileName);
if(oFile.fail())
{
cout << oFileName << " file is not opened!" << endl;
system("pause");
exit(1);
}
sortTwoFiles(iFile1, iFile2, oFile);
iFile1.close();
iFile2.close();
oFile.close();
system("pause");
return 0;
}
void sortTwoFiles(ifstream& in1, ifstream& in2,ofstream& out)
{
int x;
int y;
in1 >> x;
in2 >> y;
while(!in1.eof() && !in2.eof())
{
if(x <= y)
{
out << x << endl;
in1 >> x;
}
else
{
out << y << endl;
in2 >> y;
}
}
if(x <= y)
{
while(!in2.eof())
{
out << y << endl;
in2 >> y;
}
}
else
{
while(!in1.eof())
{
cout << x << endl;
in1 >> x;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.