Hello, this program is to merge and alphabetize two input text files and output them. (assuming files are already alphabetized) The example used is:
(input 1)
Adams C
Jones D
King B
(input 2)
Barnes A
Johnson C
The output only displays the first two and does not continue to the next line of string of data. Only this is displayed:
Adams c
Barnes A
After Barnes A is put into the out file Johnson C is read into str2. At this point in2 has reached the end of the file (all of its values have been read) so the while loop terminates.
After Barnes A is put into the out file Johnson C is read into str2. At this point in2 has reached the end of the file (all of its values have been read) so the while loop terminates.
Shouldn't while(!in1.eof() && !in2.eof()) - the && - require both in1 and in2 before terminating?
No, it requires both to not be at the end to continue doing the loop. If either fails the loop will terminate. It's read "WHILE in1 is not at the end AND in2 is not at the end continue reading" but in2 is at the end, so it doesn't continue reading.
Alright so after a while I came up with this. The problem I was having was that the original while loop did not output Johnson C and so I could not simply output the rest of input 1 after the loop. (or input 2 if the reverse were the case)
I have created another continuation to the function but I know it is not as efficient as possible. Is it possible to keep using the while loop with .eof and include the final line before terminating the loop? (outputting Johnson C) That way I would be able to output the rest of the remaining file lines. Thanks.
#include <iostream>
#include <string>
usingnamespace std;
void mergeInputs (istream& in1, istream& in2, ostream& out)
{ string str1,
str2;
getline (in1, str1);
getline (in2, str2);
while (in1 || in2)
{ // We want to continue until we have eof on both files
if (in1 && in2 && str1 < str2)
{ // Both strings are valid
out << str1 << endl;
getline(in1, str1);
continue; // go to next iteration of loop
}
if(in1 && in2 && str1 > str2)
{ // Both strings are valid
out << str2 << endl;
getline(in2, str2);
eof2 = in2.eof();
continue; // go to next iteration of loop
}
if(in1 && in2 && str1 == str2)
{ // Both strings are valid and equal
out << str2 << endl;
// Read from both files
getline(in1, str1);
getline(in2, str2);
continue; // go to next iteration of loop
}
if (in1)
{ // Write str1 (in2 is at eof)
out << str1 << endl;
getline(in1, str1);
continue; // go to next iteration of loop
}
if (in2)
{ // write str2 (in1 is at eof)
out << str2 << endl;
getline(in2, str2);
continue; // go to next iteration of loop
}
}
}