/*
Write a
program that reads in a data file of student
first names, last
names and quiz scores. Print out
the students from
highest grade to lowest, where
within a group with
the same quiz grade, students are
printed out
alphabetically by last name.
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/******
STRUCTS AND PROTOTYPES *********************/
struct Student
{
string first, last;
int
grade;
};
istream& operator>>(istream& in, Student &S);
ostream& operator<<(ostream& out, Student S);
void sort(Student *A, int
N);
void swap(Student
&studentA, Student &studentB);
// a comes before b if a has the higher grade.
// Ties are
broken by alphabetical order of last name.
// Further ties broken by alphabetical order of first name
bool before(Student a, Student b);
/****** MAIN
***************************************/
int main()
{
// Get file name and open file
string fname;
cout << "Enter file
name: ";
cin >> fname;
ifstream fin(fname.c_str());
// Allocate
array of students and read data from file
int n;
string junk;
fin >> n >> junk;
Student *S = new Student[n];
for(int i = 0; i < n && fin >> S[i]; ++i);
// Sort array
and print out array contents
sort(S,n);
for(i = 0; i < n; ++i)
cout << S[i] << endl;
return 0;
}
/******
FUNCTION DEFINITIONS ***********************/
istream& operator>>(istream& in, Student &S)
{
return in >> S.first >> S.last >> S.grade;
}
ostream& operator<<(ostream& out, Student S)
{
return out << S.first << ' ' << S.last << ' ' << S.grade;
}
bool before(Student a, Student b)
{
if(a.grade==b.grade)
if
(a.last<b.last)
return true;
else
return false;
else
if (a.grade<b.grade)
return
false;
else
return true;
}
void sort(Student *A, int
N)
{
for(int length = N; length > 1; length--)
{
// Find imax, the index of the largest
int
imax = 0, i;
for(i = 1; i < length; i++)
if (before(A[imax],A[i]))
imax = i;
swap(A[imax],A[length-1]);
}
}
void swap(Student
&studentA, Student &studentB)
{
Student temp = studentA;
studentA
= studentB;
studentB
= temp;
}