Merging two files and the output is in order.

I'm trying to write a program that reads two input files and the output lists all lines from both files by the same key field. Right now the output is showing one name twice and missing others. It also prints the wrong grades while the first grade is always a new one when ran.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream inFile1;
    ifstream inFile2;
    ofstream outFile;
    string sho1;
    string sho2;
    char i;
    char j='\0';

    inFile1.open("File1.txt");
    inFile2.open("File2.txt");

    if (!inFile1 && !inFile2)
    {
        cout<<"File cannot be opened. \n"
        <<"Program terminated."<<endl;
        return 1;
    }

    outFile.open("Outfile.txt");

    if (!outFile)
    {
        cout<<"File cannot be opened. \n"
        <<"Program terminated."<<endl;
        return 1;
    }

    do
    {
        if (sho1<sho2)
        {
            inFile1>>sho1>>i;
            outFile<<sho1<<j<<endl;
            inFile1>>sho1>>j;
        }
        else
        {
            inFile2>>sho2>>j;
            outFile<<sho2<<i<<endl;
            inFile2>>sho2>>i;
        }
    }
    while (!inFile1.eof() && !inFile2.eof());

    inFile1>>sho1>>j;
    outFile<<sho1<<j<<endl;
    inFile2>>sho2>>i;
    outFile<<sho2<<i<<endl;

    inFile1.close();
    inFile2.close();
    outFile.close();

    return 0;
}

Topic archived. No new replies allowed.