Sorting integers in a text file.

Hi! I'm trying to create a program which reads a text file which contains multiple names of students and their scores, so something like this:

Adam - 20
Bob - 17
Greg - 23
John - 19

and so on. I've created a sort code which sorts the numbers and and outputs them onto another text file. However, I've encountered a problem where the text isn't output. The integers themselves are output fine in the right order, lowest to highest, if there is no text in the file, only numbers. For example, I input 5, 9, 2, 11 into the file and run the program, the numbers will be sorted properly. But if letters were included, nothing would be output. Help would be appreciated!
Last edited on
If all you want to do is keep the scores and sort them, then read the name and don't use it.
5
6
7
8
9
10
11
12
int val;
string name;

while(in >> name >> val)
{
    studentscore.push_back(val);
}
//... 

This assumes that your input file looks something like this (no hyphens or extra characters):
Adam 20
Bob 17
Greg 23
John 19
Last edited on
? sorry could u explain better
Last edited on
Hm... my last reply disappeared into the ether.

I would use a struct to associate names and scores, but I don't know if you've learned about them yet. Instead, see if you understand how using two vectors could be helpful, one for names and another for scores:
1
2
3
4
5
6
7
8
9
10
11
12
13
    vector<string> studentNames;
    vector<int> studentScores;

    std::ifstream in;
    in.open("ScienceScores.txt");
    int val;
    string name;
    while(in >> name >> val)
    {
        studentNames.push_back(name);
        studentScores.push_back(val);
    }
    in.close();

Now, for some index i, studentNames[i] and studentScores[i] have a relationship based on the index.
You can use your current sorting code with one small addition. Every time you perform a swap inside of your "scores" vector, you need to perform a swap in the "names" vector on the exact same indices.
Topic archived. No new replies allowed.