Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Recitation 6 exercise: Write a program that reads the scores of a student from a

ID: 3851693 • Letter: R

Question

Recitation 6 exercise: Write a program that reads the scores of a student from a file into an array and writes the average score and the corresponding grade in the output file. You can download the input file "Scores txt" from moodle under recitation 8. You can name you output file as Grade txt" The input file contains scores of a student in 7 subjects with each score written on a newline. Your program must contain separate functions for reading and writing a file. You should declare the array of scores in your main function and pass it to these functions. Pass the input file name and the empty scores array to the readScores() This function should read the scores from the input file and store the scores into your array. void readScores(string inputFile, float scoresD

Explanation / Answer

// C++ code
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <string> // std::string, std::to_string
#include <math.h>
#include <fstream>

using namespace std;

void readScores(string inputFile , float scores[])
{
int i = 0;
ifstream inFile (inputFile.c_str());
if (inFile.is_open())
{
  
while(true)
{
inFile >> scores[i];
i++;

if(inFile.eof())
break;
}
inFile.close();
}

else cout << "Unable to open file";
}

void writeGrade(string outputFile , float scores[])
{
ofstream outFile;
outFile.open (outputFile.c_str());

float average = 0;
for (int i = 0; i < 7; ++i)
{
average = average + scores[i];
}

average = average/7;

char letterGrade;

if(average >= 90)
letterGrade = 'A';
else if(average >= 80)
letterGrade = 'B';
else if(average >= 70)
letterGrade = 'C';
else if(average >= 60)
letterGrade = 'D';
else
letterGrade = 'F';

outFile << "Average Score: " << average << endl << "Grade: " << letterGrade << endl;
outFile.close();
}
int main()
{
string inputFile, outputFile;

cout << "Enter input file name: ";
cin >> inputFile;
cout << "Enter output file name: ";
cin >> outputFile;

float scores[7];

readScores(inputFile,scores);

writeGrade(outputFile,scores);

return 0;
}

/*
scores.txt
75
90
88
64
100
56
82

grades.txt:
Average Score: 79.2857
Grade: C


*/