Kind of in a pickle here. I have to write a program in which I have two files that have numbers in them (already sorted in ascending order). Then, as the title mentioned, I have to merge and sort the two files into another file.
I don't get why it won't output the last 4 numbers.
This is the reason: while (!fin1.eof() && !fin2.eof())
When either file reaches eof() the loop ends. This means that if one file has more information than the other you will not get that information. You'll need another loop or two to get the remaining information.
No the loop or loops need to be after your present loop. You need to loop through the rest of the file for the file that hasn't reached eof().
By the way using eof() to control your loop is not really the best option, even though you are presently using eof() correctly. Normally you would use the results of the actual reads to control the loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
while(fin1 >> n1 && fin2 >> n2)
{
if(n1 < n2)
fout << n1 << '\n';
else
fout << n2 << '\n';
}
// This loop will only execute if fin1 is not at eof().
while(fin1 >> n1)
fout << n1 << '\n';
// This loop will only execute if fin2 is not at eof().
while(fin2 >> n2)
fout << n2 << '\n';
No need for the pre-read (line 15 and 16 of your code).
Also there is no need to close the file streams, they will close automatically when the program exits.