如何解决从文件读取并进入C ++中的Student类型的动态分配数组
我以为我对fstream和struct有一个不错的了解,但是由于某些原因,我无法弄清楚我的代码有什么问题。我正在读取的文件以代表文件中学生人数的整数'n'开头,然后用作动态分配的Student数组的大小。
我继续将文件中的每个名称,专业和年级读入Student类型的数组。但是无论出于什么原因,它只读取文件中的第一行(因为它读取名字,专业和年级),并且执行了n次。我弄乱了代码,我相信我已经将问题缩小到实际上不是n号的数组。它已正确打印出文件中的第一个int,因为我已打印出该int以确保其正常工作,并且尝试从每个学生中手动读取文件中存在相同问题的数组。
这是一项作业,因此我没有寻找任何直接的答案,但是朝正确的方向轻推将非常有用。
这是我的代码:
using namespace std;
struct Student {
string name,major;
double grade;
void display(Student);
void filterByMajor(Student[],int,string);
void filterByGrade(Student[],double);
};
int main() {
ifstream inputFile;
Student* students = nullptr;
string filename;
int n;
cout << “Enter an input file to read from: “;
cin >> filename;
inputFile.open(filename);
if (inputFile.fail()) {
cout << “ERROR: Could not open the file.” << endl;
}
else {
inputFile >> n;
students = new Student[n];
for (int i = 0; i < n; i++) {
inputFile >> students[i].name;
inputFile >> students[i].major;
inputFile >> students[i].grade;
}
cout << “ Student info” << endl;
students->display(students[0]);
cout << endl;
students->display(students[3]);
}
delete[] students;
inputFile.close();
return 0;
}
void Student::display(Student s) {
cout << “Name: “ << name << endl;
cout << “Major: “ << major << endl;
cout << “Grade: “ << grade << endl;
}
还有我正在读取的输入文件:
7 John CS 3.0 Joe Math 2.5 Jane Math 3.7 Mike CS 2.2 Carol CS 3.3 James Math 2.8 Mary CS 3.6
解决方法
问题不在于您的阅读代码。那实际上是读取文件数据就好了。真正的问题在于显示代码。您每次在数组的第一个条目上调用display()
,而display()
忽略传递给它的Student
,而是显示它的Student
的数据调用,因此您每次只能看到第一个条目的数据。
尝试以下方法:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Student {
string name,major;
double grade;
void display() const;
};
int main() {
ifstream inputFile;
Student* students = nullptr;
string filename;
int n;
cout << “Enter an input file to read from: “;
cin >> filename;
inputFile.open(filename);
if (inputFile.fail()) {
cout << “ERROR: Could not open the file.” << endl;
}
else {
inputFile >> n;
students = new Student[n];
for (int i = 0; i < n; i++) {
inputFile >> students[i].name;
inputFile >> students[i].major;
inputFile >> students[i].grade;
}
cout << “ Student info” << endl;
students[0].display();
cout << endl;
students[3].display();
}
delete[] students;
inputFile.close();
return 0;
}
void Student::display() const {
cout << “Name: “ << name << endl;
cout << “Major: “ << major << endl;
cout << “Grade: “ << grade << endl;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。