I am also a student and this is what I came up with.
Code:
/*
Robert Stout
stoutrobert@gmail.com
October 16, 2004
*/
#include <iostream>
#include <string>
using namespace std;
#define RACERS 3
struct Racer
{
string sName;
int iMinutes;
};
int Compare( const void *p1, const void *p2 )
{
Racer *r1 = (Racer *)p1;
Racer *r2 = (Racer *)p2;
return( r1->iMinutes - r2->iMinutes );
}
void main()
{
Racer racers[RACERS];
cout << "Race Evaluator" <<endl <<endl;
/////////////////////////////
// Input name and finish time
for( int i = 0; i != 3; i++ )
{
cout << "Enter the name of racer #" << i << ": ";
cin >> racers[i].sName;
cout << "Enter the finish time in minutes of racer #" << i << ": ";
cin >> racers[i].iMinutes;
}
/////////////////////////////
// Sort
// The first argument: pointer to the first element of the array.
// The second argument: number of items in the array.
// The third argument: size (in bytes) of one element of the array.
// The fourth argument: pointer to a compare function.
qsort( racers, RACERS, sizeof(Racer), Compare );
/////////////////////////////
// Display
cout << endl << "Placement Order" << endl;
cout << "Racer 1: " << racers[0].sName << endl;
cout << "Racer 2: " << racers[1].sName << endl;
cout << "Racer 3: " << racers[2].sName << endl;
}
Quote:
Console Output
Race Evaluator
Enter the name of racer #0: Ted
Enter the finish time in minutes of racer #0: 120
Enter the name of racer #1: Mark
Enter the finish time in minutes of racer #1: 304
Enter the name of racer #2: Kevin
Enter the finish time in minutes of racer #2: 214
Placement Order
Racer 1: Ted
Racer 2: Kevin
Racer 3: Mark
|
I am not a master of C++ programming, so if anyone has suggestions as to how this code could be improved I welcome comments and suggestions.