In C++. please make sure to write in file 1 and 2 Write a program that reads two
ID: 3851556 • Letter: I
Question
In C++. please make sure to write in file 1 and 2
Write a program that reads two input files whose lines are ordered by a key data field. Your program should merge these two files, writing an output file that contains all lines from both files ordered by the same key field. As an example, if two input files contain student names and grades for a particular class ordered by name, merge the information as shown below.
Using a text editor, create File 1 and File 2. You must read one line of a file at a time and either write it or the last line read from the other data file to the output file. A common merge algorithm is the following:
Write the line from file 2 to the output file and read a new line from file 2.
Write the remaining lines (if any) from file 1 to the output file.
Write the remaining lines (if any) from file 2 to the output file.
You must write the merge algorithm yourself, do not use any code from the standard template library.
Turn in: Source code and output showing test results (screen shot or picture)
Checklist:
File name included as comment at top of source file
IPO chart included as comments following the file name
Variable names are meaningful
Program compiles
Program produces correct results
Program is thoroughly tested with test output included
File 1 File 2 Output File Adams C Barnes A Adams C Jones D Johnson C Barnes A King B Johnson C Jones D King BExplanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream inputFile1, inputFile2;
ofstream outputFile;
outputFile.open ("output.txt");
inputFile1.open("file1.txt");
inputFile2.open("file2.txt");
string line1, line2;
bool flag1, flag2;
if (inputFile1.is_open() && inputFile2.is_open()) {
while ((flag1 = getline(inputFile1, line1)) && (flag2=getline(inputFile2, line2))) {
cout<<line1<<" -- "<<line2<<endl;
if(line1<line2) {
outputFile <<line1<<endl;
outputFile <<line2<<endl;
} else {
outputFile <<line2<<endl;
outputFile <<line1<<endl;
}
}
while (flag1) {
outputFile <<line1<<endl;
flag1 = getline(inputFile1, line1);
}
while (flag2) {
outputFile <<line2<<endl;
flag2 = getline(inputFile2, line2);
}
}
cout<<"File has been generated"<<endl;
inputFile1.close();
inputFile2.close();
outputFile.close();
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
File has been generated
file1.txt
Adams C
Jones D
King B
file2.txt
Barnes A
Johnson C
Output.txt
Adams C
Barnes A
Johnson C
Jones D
King B