输入一组学生信息并保存到文件中。学生信息包括学号,姓 名,5门课的分数。要求使用结构体数组做函数参数编程。 要求:使用函数原型:void Inputscore(STUDENT stu[],int n, int m) void SavetoFile(char* fname,STUD ENT stu[],int n, int m)
时间: 2024-02-27 17:59:10 浏览: 22
好的,下面是一个示例代码,你可以参考一下:
```c++
#include <iostream>
#include <fstream>
using namespace std;
// 定义学生结构体
struct STUDENT {
int id; // 学号
string name; // 姓名
int score[5]; // 五门课程的分数
};
// 从控制台输入学生信息
void Inputscore(STUDENT stu[], int n, int m) {
for (int i = 0; i < n; i++) {
cout << "请输入第" << i + 1 << "个学生的学号、姓名和五门课的分数:" << endl;
cin >> stu[i].id >> stu[i].name;
for (int j = 0; j < m; j++) {
cin >> stu[i].score[j];
}
}
}
// 将学生信息保存到文件中
void SavetoFile(char* fname, STUDENT stu[], int n, int m) {
ofstream outfile(fname, ios::out);
if (!outfile) {
cout << "无法打开文件" << fname << endl;
return;
}
for (int i = 0; i < n; i++) {
outfile << stu[i].id << " " << stu[i].name << " ";
for (int j = 0; j < m; j++) {
outfile << stu[i].score[j] << " ";
}
outfile << endl;
}
outfile.close();
cout << "学生信息已成功保存到文件:" << fname << endl;
}
int main() {
int n = 0, m = 5;
cout << "请输入学生人数:" << endl;
cin >> n;
STUDENT* stu = new STUDENT[n];
Inputscore(stu, n, m);
SavetoFile("students.txt", stu, n, m);
delete[] stu;
return 0;
}
```
这个程序会先让用户输入学生的人数,然后通过 `Inputscore` 函数从控制台输入学生信息,最后将学生信息保存到 `students.txt` 文件中。在 `SavetoFile` 函数中,我们使用了 `ofstream` 类来打开文件并写入数据。如果文件打开失败,程序会输出一个错误信息。