输入一组学生信息并保存到文件中。学生信息包括学号,姓名,5门课的分数。 要求使用结构体数组做函数参数编程。
时间: 2024-02-28 18:52:35 浏览: 72
好的,可以使用以下代码实现:
```c++
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_STUDENTS = 100; // 最大学生数
const int NUM_SUBJECTS = 5; // 科目数
// 学生结构体
struct Student {
int id; // 学号
string name; // 姓名
double scores[NUM_SUBJECTS]; // 分数
};
// 输入学生信息
void inputStudents(Student students[], int& numStudents) {
cout << "请输入学生数:";
cin >> numStudents;
for (int i = 0; i < numStudents; i++) {
cout << "请输入第 " << i+1 << " 个学生的信息:" << endl;
cout << "学号:";
cin >> students[i].id;
cout << "姓名:";
cin >> students[i].name;
cout << "五门课的分数:";
for (int j = 0; j < NUM_SUBJECTS; j++) {
cin >> students[i].scores[j];
}
}
}
// 保存学生信息到文件
void saveStudents(Student students[], int numStudents) {
ofstream fout("students.txt");
fout << numStudents << endl; // 先写入学生数
for (int i = 0; i < numStudents; i++) {
fout << students[i].id << " " << students[i].name << " ";
for (int j = 0; j < NUM_SUBJECTS; j++) {
fout << students[i].scores[j] << " ";
}
fout << endl;
}
fout.close();
}
int main() {
Student students[MAX_STUDENTS];
int numStudents;
inputStudents(students, numStudents);
saveStudents(students, numStudents);
return 0;
}
```
在此程序中,我们定义了一个 `Student` 结构体,包含了学生的学号、姓名和五门课的分数。我们使用 `inputStudents` 函数输入学生信息,并使用 `saveStudents` 函数将学生信息保存到文件中。在 `saveStudents` 函数中,我们使用了 `ofstream` 类型的对象 `fout` 来打开文件,并将学生信息写入到文件中。
注意,我们在保存学生信息时,先写入了学生数,这是为了在后面读取学生信息时方便知道需要读取多少个学生的信息。当然,读取学生信息时也需要先读取学生数。
如果想要读取保存的学生信息,可以使用以下代码:
```c++
// 从文件中读取学生信息
void loadStudents(Student students[], int& numStudents) {
ifstream fin("students.txt");
fin >> numStudents;
for (int i = 0; i < numStudents; i++) {
fin >> students[i].id >> students[i].name;
for (int j = 0; j < NUM_SUBJECTS; j++) {
fin >> students[i].scores[j];
}
}
fin.close();
}
```
这里我们使用了 `ifstream` 类型的对象 `fin` 来打开文件,并将学生信息从文件中读取到 `students` 数组中。
阅读全文
相关推荐
















