This is what I'm supposed to do:
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.
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 B
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:
Read a line from each data file
While the end of both files has not been reached
If the line from file 1 is smaller than the line from file 2
Write the line from file 1 to the output file and read
a new line from file 1.
Else
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.
Currently I am having trouble sorting alphabetically. I pretty much just copied this guy from youtube and his code worked an I understand it for the most part. I changed a few variable names and my input file is different but this my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#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;
}
|
These are the lines in my inputfile:
JonesD
KingB
AdamsC
Z
Y
X
I can moves AdamsC around and it remains alpha but zeta always results in the last name in the file, regardless of the first letter. This is completely different from the youtube video I watched so I have no idea what the problem could be.
I then have to add another file that I have to merge together into the same alphabetically sorted output file. I'm not sure how to merge the files so if someone could drop a few hints that would be awesome.