Write a C++ program that will open the text file ( class.txt ) and read the firs
ID: 646088 • Letter: W
Question
Write a C++ program that will open the text file (class.txt) and read the first name, last name and 5 scores. The program should compute the average and the grade for each student. The program should print the student first name, last name, average and the final grade in the class. Make sure that the result is printed on the screen and also sent to an output file (Grades.txt).
These are optional on this assignment:
Write a function that will calculate the average.
Write a function that will calculate the grade.
Explanation / Answer
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
void calculateAverage(ifstream& in_file, ofstream& out_file, float& avg);
char calculateGrade(float avg);
int main() {
ifstream inp;
ofstream outp;
inp.open("class.txt");
outp.open("Grades.txt");
outp << "Student Test1 Test2 Test3 Test4 Test5 Average Grade";
string name;
float average = 0;
char grade;
int k;
float avg;
for (k=1; k<=5; k++)
{
inp >> name;
outp << setw(10) << name;
calculateAverage(inp, outp, avg);
outp << setw(6) << avg;
average = average + avg;
grade = calculateGrade(avg);
outp << setw(5) <<name<< average<<" " << grade << endl;
}
average = average / 5;
outp << endl << "Class Average = " << average;
return 0;
}
void calculateAverage(ifstream& inp, ofstream& outp, float& avg)
{
int score=0, k;
float sum = 0.0;
for (k=1; k<=5; k++)
{
inp >> score;
outp << setw(4) << score << " ";
sum = sum + score;
}
avg = sum / 5;
}
char calculateGrade(float total)
{
char letter='';
if (total >= 0)
if (total >= 60)
if (total >= 70)
if (total >= 80)
if (total >= 90)
if (total > 100)
cout << "Grade can not exceed 100" << endl;
else
letter = 'A';
else
letter = 'B';
else
letter = 'C';
else
letter = 'D';
else
letter = 'F';
else
cout << "Grade can not be a negative number" << endl;
return letter;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.