我正在读取具有名称ID和等级的数据文件,并将信息存储在struc中,并使用指针数组存储struc地址。完成后,我将其动态分配给数组,然后我想在所有结构中打印名称,但什么都没打印,也没有错误消息。如何在新的动态数组中的每个结构中打印名称?
这是我的下面的代码
ifstream inFile;
Student *students[100];
string netID, studentName;
double grade1, grade2, grade3;
inFile.open("Asg3Grades.txt"); //opens the file
int counter = 0;
while(inFile.eof()){
inFile >> netID >> studentName >> grade1 >> grade2 >> grade3;
double average = (grade1+grade2+grade3)/3;
students[counter]->ID=netID;
students[counter]->name=studentName;
students[counter]->grade=average;
counter++;
}
inFile.close(); //closes the file
Student *dynamicStudents = nullptr;
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;
}
return 0;
答案 0 :(得分:2)
尝试更多类似的方法:
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;
但是,您根本不需要固定数组:
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;
}