Write a program that merges the numbers in two files and writes all the numbers
ID: 641502 • Letter: W
Question
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 it output to a third file. Each input file contains a list of numbers of type int in sorted order from the smallest to 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 out - put file stream as three arguments.
here is my code; i am unsure of how to sort the arrays; any help would be appreciated!
#include
#include
using namespace std;
void merged(ifstream& fin, ifstream& fin2, ofstream& fout);
int main()
{
//variables
ifstream fin;
ifstream fin2;
ofstream fout;
//open both files
fin.open("test1.txt");
fin2.open("test2.txt");
fout.open("merged.txt");
if(fin.fail())
{
cout << "Fail to open text document" << endl;
}
if(fin2.fail())
{
cout << "Fail to open text document" << endl;
}
merged(fin,fin2,fout);
fin.close();
fin2.close();
fout.close();
return 0;
}
void merged(ifstream& fin, ifstream& fin2, ofstream& fout)
{
int file1[5];
int file2[5];
int i = 0, j = 0;
while(!fin.eof() && !fin2.eof())
{
fin >> file1[i];
fin2 >> file2[j];
i++;
j++;
}
for(int k = 0; k < 10; k++)
{
if(file1[k] <= file2[k])
{
fout << file1[k] << endl;
}
else
{
fout << file2[k] << endl;
}
}
}
Explanation / Answer
implement like this..hope it helps...
int c [] = new int[file1.length+file2.length];
int j=0;
for (int i = 0;i<b=file2.length;i++){
while(file2[i]>file1[j]){
c[j] = file1[j] ;
j++;
}
if(file2[i] == file1[j]){
c[j] = file2[i];
c[j+1] = file1[j];
}
c[j] = file2[i];
j++;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.