Попробуйте что-нибудь еще подобное:
ifstream inFile;
Student students[100];
int counter = 0;
string line, netID, studentName;
double grade1, grade2, grade3;
inFile.open("Asg3Grades.txt"); //opens the file
while (getline(inFile, line)) {
istringstream iss(line);
if (iss >> netID >> studentName >> grade1 >> grade2 >> grade3) {
double average = (grade1 + grade2 + grade3) / 3;
students[counter].ID = netID;
students[counter].name = studentName;
students[counter].grade = average;
if (++counter == 100) break;
}
}
inFile.close(); //closes the file
Student *dynamicStudents = new Student[counter];
for (int i = 0; i < counter; i++) {
dynamicStudents[i] = students[i];
}
for (int i = 0; i < counter; i++) {
cout << dynamicStudents[i].name << endl;
}
delete[] dynamicStudents;
Live Demo
Хотя вам не нужен фиксированный массив вообще:
ifstream inFile;
Student* students = nullptr;
int counter = 0, capacity = 0;
string line, netID, studentName;
double grade1, grade2, grade3;
inFile.open("Asg3Grades.txt"); //opens the file
while (getline(inFile, line)) {
istringstream iss(line);
if (iss >> netID >> studentName >> grade1 >> grade2 >> grade3) {
double average = (grade1+grade2+grade3)/3;
if (counter == capacity)
{
Student *temp = new Student[capacity + 100];
for (int i = 0; i < counter; ++i)
temp[i] = students[i];
delete[] students;
students = temp;
capacity += 100;
}
students[counter].ID = netID;
students[counter].name = studentName;
students[counter].grade = average;
++counter;
}
}
inFile.close(); //closes the file
for (int i = 0; i < counter; ++i) {
cout << students[i].name << endl;
}
delete[] students;
Демонстрационная версия
Что можно еще больше упростить, используя std::vector
вместо new[]
:
ifstream inFile;
vector<Student> students;
string line, netID, studentName;
double grade1, grade2, grade3;
inFile.open("Asg3Grades.txt"); //opens the file
while (getline(inFile, line)) {
istringstream iss(line);
if (iss >> netID >> studentName >> grade1 >> grade2 >> grade3) {
double average = (grade1+grade2+grade3)/3;
Student student;
student.ID = netID;
student.name = studentName;
student.grade = average;
students.push_back(student);
}
}
inFile.close(); //closes the file
for (size_t i = 0; i < student.size(); ++i) {
cout << students[i].name << endl;
}
Демоверсия