I am trying to do a program where a user inputs three names and they get sorted. The conditions are that each name gets inputted like "firstname lastname" and then I need to sort the names on lastname, but if the lastname is the same for two entries I need to sort on the firstname.
I have solved how to sort on just the firstname OR lastname, but am getting stuck on how to sort on both. Any ideas how I can implement more conditional sorting without using an array or in c++?
For each input I do this to split the input to firstname and lastname to lowercase:
cout << "Input name1: " << endl;
getline(cin, input1);
input1_old = input1;
size_t found = input1.find(space);
for (int i = 0; i < input1.size(); i++)
{
input1[i] = tolower(input1[i]);
}
input1Last = input1.substr(found + 1, string::npos);
input1First = input1.substr(0, found);
Then I "sort" like this:
if (input1Last <= input2Last && input2Last <= input3Last)
{
cout << input1_old << '\n' << input2_old << '\n' << input3_old << endl;
}
else if (input1Last <= input3Last && input3Last <= input2Last)
{
cout << input1_old << '\n' << input3_old << '\n' << input2_old << endl;
}
else if (input2Last <= input1Last && input1Last <= input3Last)
{
cout << input2_old << '\n' << input1_old << '\n' << input3_old << endl;
}
else if (input2Last <= input3Last && input3Last <= input1Last)
{
cout << input2_old << '\n' << input3_old << '\n' << input1Last << endl;
}
else if (input3Last <= input1Last && input1Last <= input2Last)
{
cout << input3_old << '\n' << input1_old << '\n' << input2_old << endl;
}
if (input3Last <= input2Last && input2Last <= input1Last)
{
cout << input3_old << '\n' << input2_old << '\n' << input1Last << endl;
}
Aucun commentaire:
Enregistrer un commentaire