Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CODE in C++ Write a program that merges the numbers in two files and writes all

ID: 3728473 • Letter: C

Question

CODE in C++

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 to 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 at least one function that is called with the two input-file streams and the output-file stream as three arguments. The list of numbers are not necessary of the same length. Aske the user for each file name and test if the file exit. Show the content of all three files on a screen

Sample input file 1:

22

44

55

77

99

500

Sample input file 2:

11

55

101

Sample output file:

11

22

44

55

55

77

99

101

500

Sample output screen:

While Entering TiTe names, pT ease enter the Tile hame fol lowed by extension. Enter the first of two input file names: inNamel.txt Now a second input file name i nName2.txt Enter the output file name. WARNING:ANY EXISTING FILE WITH THIS NAME WILL BE ERASED. outName. txt Contents of file inName1.txt are: 500 Contents of file inName2.txt are: 101 Contents of merged file, outName. txt are: 101 500 Press any key to continue .. .

Explanation / Answer

C++ program :-

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

void merge_files(ifstream fd1,ifstream fd2,ofstream fdout){

int n1, n2;

while(fd1 >> n1 && fd2 >> n2)

{

if(n1 < n2)

fdout << n1 << ' ';

else

fdout << n2 << ' ';

}

// This loop will only execute if fd1 is not at eof().

while(fd1 >> n1)

fdout << n1 << ' ';

// This loop will only execute if fd2 is not at eof().

while(fd2 >> n2)

fdout << n2 << ' ';

}

int main()

{

ifstream fd1, fd2;

ofstream fdout;

string fileName;

cout<<"Enter the first of the two input file names:"<<endl;

cin>>fileName;

fd1.open(fileName.c_str());

cout<<"Now a second input file names:"<<endl;

cin>>fileName;

fd2.open(fileName.c_str());

cout<<"Enter the output file name:"<<endl;

cout<<"WARNING:ANY EXISTING FILE WITH THIS NAME WILL BE ERASED"<<endl;

cin>>fileName;

fdout.open(fileName.c_str());

merge_files(fd1,fd2,fdout);

fd1.close();

fd2.close();

fdout.close();

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote