Merge and Sort Two Files Into Another File

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.

Here's the text from my files

1
2
3
4
5
intext1.txt:
2 4 6 8 10 12 14 16 18

intext2.txt:
1 3 5 7 9 11 13 15 


My code sorts and merges the files, but it only does so until 13. So the output of my third file is something like this.
1
2
outtext.txt
1 2 3 4 5 6 7 8 9 10 11 12 13


I don't get why it won't output the last 4 numbers. Here's 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
38
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream fin1, fin2;
    ofstream fout;
    int n1, n2;

    fin1.open("intext1.txt");
    fin2.open("intext2.txt");
    fout.open("outtext.txt");

    fin1 >> n1;
    fin2 >> n2;

    while (!fin1.eof() && !fin2.eof())
    {
        if (n1 < n2)
        {
            fout << n1 << endl;
            fin1 >> n1;
            //fin1.ignore(5, '\n');
        }
        else
        {
            fout << n2 << endl;
            fin2 >> n2;
            //fin2.ignore(5, '\n');
        }
    }
    fin1.close();
    fin2.close();
    fout.close();
}

Last edited on

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.
as long as I have another loop inside, the while (!fin1.eof() && !fin2.eof()) is fine?
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.
Last edited on
Gotcha, thanks!
Topic archived. No new replies allowed.