Write a program that merges the integer numbers in two sorte
Solution
// C++ code merge two files
#include <fstream> // file processing
#include <iostream> // cin and cout
#include <cctype> // toupper
#include <iomanip> // setw
#include <cstring> // cstring functions strlen, strcmp, strcpy stored in string.h
#include <string.h> // string class
#include <stdlib.h>
#include <vector>
using namespace std;
void merge(std::istream& file1,std::istream& file2, std::ostream& fout)
{
std::vector<int> v1;
std::vector<int> v2;
int d1;
int d2;
while (!file1.eof())
{
file1 >> d1;
v1.push_back(d1);
}
while (!file2.eof())
{
file2 >> d2;
v2.push_back(d2);
}
int i = 0, j = 0;
while(i < v1.size() && j < v2.size())
{
if(v1[i] < v2[j])
{
fout << v1[i] << endl;
i++;
}
else
{
fout << v2[j] << endl;
j++;
}
}
while (i < v1.size())
{
fout << v1[i] << endl;
i++;
}
while (j < v2.size())
{
fout << v2[j] << endl;
j++;
}
}
int main()
{
string fname1,fname2,fname3;
cout<<\"Enter name for input file-1: \";
cin >> fname1;
cout<<\"Enter name for input file-2: \";
cin >> fname2;
cout<<\"Enter name of output file: \";
cin >> fname3;
std::ifstream file1(fname1.c_str());
std::ifstream file2(fname2.c_str());
std::ofstream fout(fname3.c_str());
if (!file1.good() || !file2.good() || !fout.good())
{
std::cout << \"Error opening file(s)\" << std::endl;
return 0;
}
merge(file1,file2,fout);
file1.close();
file2.close();
fout.close();
return 0;
}
/*
output:
Enter name for input file-1: input1.txt
Enter name for input file-2: input2.txt
Enter name of output file: output.txt
input1.txt
2
6
10
12
17
input2.txt
4
8
9
15
output.txt
2
4
6
8
9
10
12
15
17
*/


