The program I'm building is meant to output students names, their 5 scores, and their grade from a input file named "students.txt" into an output file named "output.txt". All of the calculation required is correct, but the formatting of the output file is not, as I want all of the scores and grades to be aligned under their titles. I was under the impression that setw included within it the text it's applied to, but it seems to be applied inconsistently in the same file, to my knowledge. I know that the problem lies with the differing lengths of the names being used, I just don't know how to solve that, as I thought setw was supposed to be used for formatting in that circumstance. This is the code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
struct studentType
{
int scores[5];
string fName;
string lName;
char grade;
};
void read(ifstream& inFile, studentType students[], int numStudents);
void calcGrade(studentType students[], int numStudents);
void print(ofstream& outFile, studentType students[], int numStudents);
int main()
{
ifstream inFile;
ofstream outFile;
const int numStudents = 12;
studentType students[20];
inFile.open("students.txt");
outFile.open("output.txt");
read(inFile, students, numStudents);
calcGrade(students, numStudents);
print(outFile, students, numStudents);
inFile.close();
outFile.close();
return 0;
}
void read(ifstream& inFile, studentType students[], int numStudents)
{
for (int i = 0; i < numStudents; i++)
{
inFile >> students[i].fName >> students[i].lName;
for (int i2 = 0; i2 < 5; i2++)
inFile >> students[i].scores[i2];
inFile.ignore(100, '\n');
}
}
void calcGrade(studentType students[], int numStudents)
{
double averageScore;
for (int i = 0; i < numStudents; i++)
{
int aggregateScore = 0;
for (int i2 = 0; i2 < 5; i2++)
aggregateScore += students[i].scores[i2];
averageScore = aggregateScore / 5;
if (averageScore >= 90)
students[i].grade = 'A';
else if (averageScore >= 80)
students[i].grade = 'B';
else if (averageScore >= 70)
students[i].grade = 'C';
else if (averageScore > 60)
students[i].grade = 'D';
else
students[i].grade = 'F';
}
}
void print(ofstream& outFile, studentType students[], int numStudents)
{
outFile << right << "Name" << setw(40) << "Scores" << setw(30) << "Grade" << endl;
for (int i = 0; i < numStudents; i++)
{
outFile << right << students[i].fName << " " << students[i].lName << setw(20);
for (int i2 = 0; i2 < 5; i2++)
outFile << right << " " << students[i].scores[i2];
outFile << right << setw(20) << students[i].grade << endl;
}
}
This is what I'm getting in the output file:
Name Scores Grade
ARCHIE ANDREW 90 80 70 90 80 B
BETTY COOPER 100 100 100 100 100 A
VERONICA LODGE 70 70 70 80 80 C
TARA DREW 90 80 78 90 89 B
NANCY COOPER 100 100 10 90 100 B
RONI DODGE 70 77 70 88 80 C
RICHIE DREW 90 80 70 90 80 B
BELLA HOOPER 100 100 100 100 100 A
NINA HODGE 70 70 70 80 80 C
CLARA DEW 90 80 78 90 89 B
FANCY COOP 100 100 10 90 100 B
RINA EDGE 70 77 70 88 80 C