Class Exercise Solution
#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <iomanip.h>
class student{
public:
enum grade{A, B, C, D, F};
student(char* ,float ,float );
~student();
void print();
private:
void compute_total();
char *student_id;
float exam1;
float exam2;
float total;
grade letter_grade;
};
student::student(char* sid, float ex1, float ex2) : exam1(ex1),
exam2(ex2){
student_id = new char[strlen(sid)+1];
strcpy(student_id, sid);
compute_total();
}
student::~student(){
delete [] student_id;
}
void student::compute_total(){
total = exam1+exam2;
const float grade_array[] = {90.0, 75.0, 60.0, 50.0};
for(int i=0; i<4; i++){
if(total >= grade_array[i]) break;
}
switch(i){
case 0: letter_grade = A;
break;
case 1: letter_grade = B;
break;
case 2: letter_grade = C;
break;
case 3: letter_grade = D;
break;
default: letter_grade = F;
break;
}
}
void student::print(){
char grade;
switch(letter_grade){
case A: grade = 'A';
break;
case B: grade = 'B';
break;
case C: grade = 'C';
break;
case D: grade = 'D';
break;
case F: grade = 'F';
break;
}
cout.setf(ios::fixed | ios::left);
cout.precision(2);
cout << setw(20) << "Student ID" << setw(9) << "Exam 1";
cout << setw(9) << "Exam 2" << setw(9) << "Total";
cout << setw(9) << "Grade" << endl;
cout << setw(20) << student_id << setw(9) << exam1;
cout << setw(9) << exam2 << setw(9) << total;
cout << setw(9) << grade << endl;
}
int main(){
char id[8];
float ex1, ex2;
student* studentptr[3];
ifstream fin("grades.dat");
fin >> id >> ex1 >> ex2;
for (int i=0; !fin.eof(); i++){
studentptr[i] = new student(id, ex1, ex2);
fin >> id >> ex1 >> ex2;
}
for (int j=0; j < 3; j++){
studentptr[j]->print();
}
for (j=0; j < 3; j++){
delete studentptr[j];
}
return(0);
}
Output:
Student ID Exam 1 Exam 2 Total Grade
s999999 45.00 50.00 95.00 A
Student ID Exam 1 Exam 2 Total Grade
s888888 40.00 42.00 82.00 B
Student ID Exam 1 Exam 2 Total Grade
s777777 47.00 22.00 69.00 C
Back to Previous Page
Document:
Local Date:
Last Modified On: