In C++ Read from the file (assignment3.txt) that is attached on and calculate th
ID: 3850668 • Letter: I
Question
In C++
Read from the file (assignment3.txt) that is attached on and calculate the average of all the grades. The values that you are reading are percentage grades from 1 – 100. After this done you will need to say if the student passed (50 percent and higher). You will then need to write the properties to a text file. The output should resemble the table below (must include % in the output. You will need to print the average at the end of the list. And if the average is a pass/fail and the highest and smallest mark. The output file name is grades.txt.
the below is the format:
Student Grade Pass/Fail
1 37% Fail
2 63% Pass
The average is 50%. The average is a pass. The highest mark was 63 and the lowest mark was 37.
(assignment3.txt) data
Explanation / Answer
main.cpp:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
fstream input("assignment3.txt", std::ios_base::in);
if(input == NULL) {
cout << "Error!! unable to read file." << endl;
return 1;
}
// marks will be required to read the data from file
// totalmarks and count will be required to find the average
int marks=0, totalMarks=0;
int count = 0;
int max = 0, min = 100;
// keep reading the marks from file
while (input >> marks)
{
// update min and max marks if required
if(marks > max)
max = marks;
if(marks < min)
min = marks;
// update count and total marks
totalMarks += marks;
count++;
}
string minStatus = (min < 50)?"Fail":"Pass";
string maxStatus = (max < 50)?"Fail":"Pass";
double average = (double)totalMarks/count;
string averageStatus = (average < 50)?"Fail":"Pass";
fstream output("grades.txt", std::ios_base::out);
output << "Student Grade Pass/Fail" << endl;
output << "1 " << setw(4) << min << "% " << minStatus << endl;
output << "2 " << setw(4) << max << "% " << maxStatus << endl;
output << "The average is " << average << "%. The average is a " << averageStatus << ".";
output << "The highest mark was " << max << " and the lowest mark was " << min << "." << endl;
cout << "Program completed Successfully!!" << endl;
return 0;
}
assignment3.txt:
26 99 85 97 61 37 31 72 71 53 22 10 13 18 55 97 97 99 100 81 83 51 53 57 65 32 19
grades.txt:
Student Grade Pass/Fail
1 10% Fail
2 100% Pass
The average is 58.6667%. The average is a Pass.The highest mark was 100 and the lowest mark was 10.