I'm trying to sort names alphabetically e.g If user enters names and GPA:
Names GPA
Peter 2.8
Robert 5.6
David 7.8
The output should be : -
Names GPA
David 7.8
Peter 2.8
Robert 5.6
Here is my program so far (INCOMPLETE):-
#include <iostream>
using namespace std;
int main()
{
char name [5][25];
float gpa [5];
int i;
for (i=0 ; i<5 ; i++)
{
cout << "Enter name " << i+1 << " : ";
cin >> name [i];
cout << "Enter GPA : ";
cin >> gpa [i];
cout << endl;
}
cout << "\n********** Your entered data **********\n\n";
cout << "\tName" << "\t\t" << "GPA\n\n";
for (i=0 ; i<5 ; i++)
{
cout << "\t" << name [i] << "\t\t" << gpa [i];
cout << endl;
}
for (i=0 ; i<5 ; i++)
{
for (int j=0 ; j<1 ; j++)
{
cout << (int) name [i][j] << endl;
}
}
cout << "\n\n******* Sorted data (w.r.t name) *******\n\n";
cout << "\tName" << "\t\t" << "GPA\n\n";
for (i=0 ; i<5 ; i++)
{
cout << "\t" << name [i] << "\t\t" << gpa [i];
cout << endl;
}
cout << endl;
return 0;
}
Remember, only name should be sorted alphabetically. I have taken the ASCII values of the first characters of entered names in the middle for
loop but:-
1- ASCII code for 's' is not the same as 'S' (That's a problem for me)
2- I can't seem create a logic to compare the ASCII values of the first letters of names then sort them accordingly. Then afterwards linking the name with the sorted letter list and displaying the result. Also the GPA should be linked with the names.
Any help would be appreciated.
If you convert the names' character to upper-case using
std::toupper
you should then just be able to compare the the strings using < operator.Edit: if you don't want to use
std::sort
:-)