// // scores.cpp // CSC 215 // John Rogers // // This program reads a file where each line contains // a student's last name and a test score. It prints // out the student's name and the score. // At the end of the report, it prints out the number // of students processed and the average of all the // test scores. // #include #include #include void openFile(ifstream& studentfile); void closeFile(ifstream& studentfile); void printLine(char *lastname, int score); void printSummary(int studentcount, int totalscore); int main() { char lastname[16]; int score, totalscore = 0, studentcount = 0; ifstream studentfile; openFile(studentfile); while (studentfile >> lastname >> score) { studentcount++; totalscore += score; printLine(lastname, score); } closeFile(studentfile); printSummary(studentcount, totalscore); return 0; } // // Connect the input file stream object studentfile // to the file whose name is given by the user. // Exit the program if the open failed more than 3 times. // void openFile(ifstream& studentfile) { char studentfileName[51]; // Assume that the name is 50 chars or less. int errorcount = 0; do { cout << "Enter the pathname of the file containing the " << "student data: "; cin >> studentfileName; studentfile.open(studentfileName); if (studentfile.fail()) { cout << "Unable to open the file " << studentfileName << endl; errorcount++; if (errorcount > 3) { exit(1); } } } while (studentfile.fail()); return; } // // Print a report line containing the last name and // the scores. // void printLine(char *lastname, int score) { cout.setf(ios::left); cout.width(15); cout << lastname << " "; cout.setf(ios::right); cout.width(3); cout << score << endl; return; } // // Print the summary at the end of the report. // void printSummary(int studentcount, int totalscore) { cout << endl << endl; cout << "Total number of students: " << studentcount << endl; cout.precision(2); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << "Combined average: " << double(totalscore) / studentcount << endl << endl; return; } // // Close the student file. // void closeFile(ifstream& studentfile) { studentfile.close(); return; }