私が構築しているプログラムは、「students.txt」という名前の入力ファイルから「output.txt」という名前の出力ファイルに、生徒の名前、5 つのスコア、および成績を出力することを目的としています。必要な計算はすべて正しいのですが、すべてのスコアとグレードをタイトルの下に配置したいので、出力ファイルのフォーマットが正しくありません。setw には、適用されるテキストが含まれているという印象を受けましたが、私の知る限り、同じファイル内で矛盾して適用されているようです。問題は使用されている名前の長さが異なることにあることはわかっていますが、 setw はその状況でのフォーマットに使用されるはずだったので、それを解決する方法がわかりません。これはコードです:
#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;
}
}
これは、出力ファイルで取得しているものです。
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