Sorting Array of Struct

Hi everyone! I'm still a beginner at this and totally lost on sorting. I am taking this as a distance learning class so the book is the only reference I have. This program asks the user to input student name and score. It is supposed to display the student data in ascending score order. I can get the program to work but not the sort function. Any help would be greatly appreciated!

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

struct Student
{
string name;
int score;
};

// Function prototype
string getName();
int getScore();
float getAverage(int, float);
void sortScore(Student[],int);

int main()
{
Student *pStud;
int num;
float total = 0.0;
float average = 0.0;

// User enters the number of students (array size)
cout << "Enter the number of students: " << endl;
cin >> num;

pStud = new Student[num];

for (int i = 0; i < num; i++)
{
pStud[i].name = getName();
pStud[i].score = getScore();
}

for (int k = 0; k < num; k++)
{
total += pStud[k].score;
}

sortScore(pStud, num);
average = getAverage(num, total);

cout << left << setw(30) << "Name" << right << setw(6) << "Score" << endl;
cout << "------------------------------------" << endl;
for (int count = 0; count < num; count++)
{
cout << left << setw(30) << pStud[count].name << right << setw(6) << pStud[count].score << endl;
}
cout << "------------------------------------" << endl;
cout << left << setw(30) << "Average" << right << fixed << setprecision(1) << setw(6) << average << endl;
}

string getName()
{
string name;
cout << "Enter student name: ";
cin.ignore();
getline(cin, name);
return name;
}

int getScore()
{
int score;
do
{
cout << "Enter student's score: ";
cin >> score;
if (score < 0 || score > 105)
{
cout << "Invalid entry. Enter score between 0 and 105: ";
}
} while (score < 0 || score > 105);
return score;
}

float getAverage(int n, float t)
{
float avg;
avg = t/n;
return avg;
}

void sortScore(Student score[], int size)
{
Student temp;
bool swap;

do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (score[count].getScore() > score[count + 1].getScore())
{
temp = score[count];
score[count] = score[count + 1];
score[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
Where have you defined a class member function named getScore() for your Student structure?

And since the default access for a structure is public why are you trying to use a member function instead of just directly accessing the value?



If I take off getScore, how will it know to sort scores then rearrange names to match the scores?
Use the member variable score.

if (score[count].score > score[count + 1].score)
It works! Thank you so much for all your help jlb!
Topic archived. No new replies allowed.