//----------------------------------------------- // LetterGrade2.cpp // // Given a list of test scores, determine the // corresponding letter grades. // // Demonstrate a structure containing an array. // // D. Searls // Asbury College // Sept. 2006 //----------------------------------------------- #include<iostream> #include<iomanip> #include<fstream> using namespace std; const int MAXSIZE = 100; struct testRecord { int score; // Test score (0 to 100) char grade; // Corresponding letter grade }; struct testData { testRecord list[MAXSIZE]; // List of test records int n; // Number of records in list }; void readTestScores(testData&); void determineLetterGrades(testData&); void displayResults(testData); int main() { testData myData; readTestScores(myData); determineLetterGrades(myData); displayResults(myData); return 0; } //----------------------------------------------- // readTestScores // // Read the test scores into the data structure. // // Out Parameter: data //----------------------------------------------- void readTestScores(testData& data) { ifstream infile; int testScore; infile.open("allscores.txt"); if (infile.fail()) { cout << "FATAL ERROR: Could not open input file." << endl; cout << "Program Execution Terminated." << endl << endl; exit(0); } data.n = 0; infile >> testScore; while (!infile.fail() && data.n < MAXSIZE) { data.list[data.n].score = testScore; infile >> testScore; data.n = data.n + 1; } if (!infile.fail()) { cout << "ERROR: Too many test scores for this program." << endl; cout << "Only the first " << MAXSIZE << " scores were read." << endl; cout << endl; } } //----------------------------------------------- // letterGrade // // Given a test score in the range 0 to 100, this // function returns the corresponding letter // grade. // // Pre-condition: 0 <= score <= 100 // // In Parameter: score //----------------------------------------------- char letterGrade(int score) { char grade; if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } return grade; } //----------------------------------------------- // determineLetterGrades // // Given a list of test scores, find the // corresponding letter grades. // // In/Out Parameter: myData //----------------------------------------------- void determineLetterGrades(testData& myData) { for (int i = 0; i < myData.n; i++) { myData.list[i].grade = letterGrade(myData.list[i].score); } } //----------------------------------------------- // displayResults // // Display the scores and corresponding grades. // // In Parameter: testInfo //----------------------------------------------- void displayResults(testData testInfo) { cout << "Score Grade" << endl; cout << "----- -----" << endl; for (int i = 0; i < testInfo.n; i++) { cout << setw(5) << testInfo.list[i].score; cout << setw(5) << testInfo.list[i].grade; cout << endl; } }