一部のデータを読み取る必要があるプログラムを作成しようとしています。ファイルを開いてデータを読み込むことはありません。機能のあるもののようgetData
です。
#include <iostream>
#include <iomanip>
#include <string>
#include <climits>
#include <fstream>
using namespace std;
const int NUM_STUDENTS = 20;
const int NUM_GRADES = 5;
struct StudentType {
string name;
int grades[NUM_GRADES];
int average;
char letterGrade;
};
void getData(StudentType students[]);
void printGrades(StudentType students[]);
void assignGrades(StudentType students[]);
string convert(string name);
float findHighest(StudentType students[]);
void printHighest(StudentType students[]);
int main()
{
StudentType students[20];
getData(students);
printGrades(students);
return 0;
}
void getData(StudentType students[]) {
string name, filename;
ifstream fin;
cout << "Please Enter the file name: ";
cin >> filename;
fin.open(filename.c_str());
while (!fin) {
cout <<"Could not open " << filename << ", please re-enter the filename" << endl;
cout << "Please Enter the file name: ";
cin >> filename;
fin.open(filename.c_str());
}
for (int index = 0; index < NUM_STUDENTS; ++index) {
int total = 0;
getline(fin, name);
students[index].name = convert(name);
for (int i = 0; i <NUM_GRADES; ++i) {
fin >> students[index].grades[NUM_GRADES];
fin.ignore(INT_MAX, '\n');
total = total + students[index].grades[NUM_GRADES];
}
students[index].average = static_cast<float>(total)/NUM_GRADES;
}
fin.close();
}
string convert(string name) {
string s;
string:: size_type x;
x = name.find(".");
if (x != string::npos) {
++x;
}
else {
x = name.find( " ");
}
s = name.substr(x+1, name.size()) + ", " + name.substr(0,x);
return s;
}
void printGrades(StudentType students[]) {
for (int index = 0; index < NUM_STUDENTS; ++index) {
cout << students[index].name;
cout << " ";
for (int i = 0; i <NUM_GRADES; ++i) {
cout << students[NUM_STUDENTS].grades[NUM_GRADES];
cout << " ";
}
cout << students[NUM_STUDENTS].average;
}
}
void assignGrades(StudentType students[]) {
for (int index = 0; index < NUM_STUDENTS; ++index) {
if (students[NUM_STUDENTS].average < 60)
students[NUM_STUDENTS].letterGrade = 'F';
else if (students[NUM_STUDENTS].average < 70)
students[NUM_STUDENTS].letterGrade = 'D';
else if (students[NUM_STUDENTS].average < 80)
students[NUM_STUDENTS].letterGrade = 'C';
else if (students[NUM_STUDENTS].average < 90)
students[NUM_STUDENTS].letterGrade = 'B';
else
students[NUM_STUDENTS].letterGrade = 'A';
}
}
float findHighest(StudentType students[]) {
float highestAverage = 0;
for (int index = 0; index < NUM_STUDENTS; ++index) {
if (students[index].average > highestAverage)
highestAverage = students[index].average;
}
return highestAverage;
}
void printHighest(StudentType students[]) {
float highestAverage = findHighest(students);
cout << "The name(s) of the student(s) with the Highest average are ";
for (int index = 0; index < NUM_STUDENTS; ++index) {
if (students[index].average == highestAverage)
cout << students[index].name << " ";
}
}