C++ problem with sorting grades
Hello I am pretty new to C++
I am having some problems fixing the code below.
If I input scores and names such as Sam "100" and John "20" it will sort them correctly in ascending order
"Sam 20
"John,100"
If I do it the opposite way around Sam "20" and then John "100"
it ignores the name assigned to the "20"
Also is there a simple way to list the unsorted list before the sorted list.
Thank you in advance for any advice provided
Code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct StudentGrades
{
string name;
double grade;
};
void sort (StudentGrades *score, int size);
int main ()
{
StudentGrades *sGrade;
int mass;
cout << "Please enter the amount of student grades you wish to enter \n";
cin >> mass;
sGrade = new StudentGrades[mass];
for (int index = 0; index < mass; index ++)
{
cout << "Please enter the [NAME] of student #" << (index + 1) << ": ";
cin >> (sGrade + index)->name;
cout << "Please enter the [SCORE] of student #" << (index + 1) << ": ";
cin >> (sGrade + index)->grade;
while (sGrade[index].grade < 0)
{
cout << "Negative numbers are not accepted, please try again with positive values \n";
cin >> (sGrade + index)->grade;
}
}
cout << "The sorted names and scores are:";
cout << endl;
sort (sGrade, mass);
//cout << fixed << showpoint << setprecision(2);
delete []sGrade;
sGrade = 0;
system ("pause");
return 0;
}
void sort (StudentGrades *score, int size)
{
int minIdx;
double minGrade;
string id;
for (int scan = 0; scan < (size - 1); scan ++)
{
minIdx = scan;
minGrade = (score + scan)->grade;
for (int count = scan + 1; count < size; count ++)
{
if ((score + count)->grade < minGrade)
{
minGrade = (score + count)->grade;
minIdx = count;
id = (score + count)->name;
}
}
(score + minIdx)->grade = (score + scan)->grade;
(score + scan)->grade = minGrade;
(score + minIdx)->name = (score + scan)->name;
(score + scan)->name = id;
}
for (int count = 0; count < size; count ++)
{
cout << (score + count)->name << " ";
cout << (score + count)->grade << " ";
cout << endl;
}
}