Alphabetical Order!!

I am trying to finish my program where I have to print the two merging files in Alphabetical order by Last Name along with the score. NO ARRAY!! Here's what I have so far..
#include <iostream>
using namespace std;
#include <fstream>
#include <cstdlib>
#include <string>

struct person
{
string first, last;
int score;
};

int main()
{

ifstream data1, data2;
data1.open("data1.txt");
if(!data1)
{
cerr << "Error: data1 could not be opened" << endl;
exit(1);
}

data2.open("data2.txt"); // opens the file
if(!data2) // file couldn't be opened
{
cerr << "Error: data2 could not be opened" << endl;
exit(2);
}

person rec1;
data1 >> rec1.first >> rec1.last >> rec1.score;
while (!data1.eof())
{
cout << rec1.last << ", " << rec1.first << " " << rec1.score << endl;
data1 >> rec1.first >> rec1.last >> rec1.score;
}

person rec2;
data2 >> rec2.first >> rec2.last >> rec2.score;
while (!data2.eof())
{
cout << rec2.last << ", " << rec2.first << " " << rec2.score << endl;
data2 >> rec2.first >> rec2.last >> rec2.score;
}

data1.close();
data2.close();
return 0;
}
Last edited on
Now that you have the names, you can do a simple thing such as:

1
2
3
4
5
6
7
8
9
10
if (rec1.last > rec2.last)
{
    cout << rec1.last << ", " << rec1.first << " " << rec1.score << endl;
    cout << rec2.last << ", " << rec2.first << " " << rec2.score << endl;
}
else
{
    cout << rec2.last << ", " << rec2.first << " " << rec2.score << endl;
    cout << rec1.last << ", " << rec1.first << " " << rec1.score << endl;
}
Last edited on
where would I add it cause I put it ad the end but it's still not printing in alphabetical order? Thanks

Here's what I did...
..........
.....
data1.close();
data2.close();
return 0;

if (rec1.last > rec2.last)
{
cout << rec1.last << ", " << rec1.first << " " << rec1.score << endl;
cout << rec2.last << ", " << rec2.first << " " << rec2.score << endl;
}
else
{
cout << rec2.last << ", " << rec2.first << " " << rec2.score << endl;
cout << rec1.last << ", " << rec1.first << " " << rec1.score << endl;
}
}
Last edited on
Topic archived. No new replies allowed.