Write a program that reads two input files whose lines are ordered by a key data
ID: 3851228 • Letter: W
Question
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 <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream ifile1;
string name;
string alpha;
string zeta;
int flag = 0;
ifile1.open("File1.txt");
while (ifile1 >> name) {
if (flag == 0){
alpha = name;
zeta = name;
flag++;
}
else {
if (name < alpha){
alpha = name;
}
else if (alpha < name){
zeta = name;
}
}
}
ifile1.close();
cout << "First is" << alpha;
cout << "last is" << zeta;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.