定义一个结构体数组存放十个学生的学号,姓名和成绩,从键盘输入这十个学生的以上内容,存入文件stud.txt,关闭文件,打开文件,将数据读出,查看是否正确再关闭文件,打开文件,读出数据,将十个学生按照平均分进行由高到低的排序,分别将结果输出到屏幕上和另一个文件studsort.txt中
时间: 2023-10-07 18:06:52 浏览: 83
以下是代码实现:
```c++
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int MAX_STUDENTS = 10;
struct Student {
int id;
string name;
double score;
};
bool compare(const Student& s1, const Student& s2) {
return s1.score > s2.score;
}
int main() {
Student students[MAX_STUDENTS];
// 从键盘输入学生信息
for (int i = 0; i < MAX_STUDENTS; i++) {
cout << "请输入第" << i+1 << "个学生的学号、姓名和成绩:";
cin >> students[i].id >> students[i].name >> students[i].score;
}
// 存入文件stud.txt
ofstream ofs("stud.txt");
if (!ofs) {
cerr << "无法打开文件" << endl;
return 1;
}
for (int i = 0; i < MAX_STUDENTS; i++) {
ofs << students[i].id << " " << students[i].name << " " << students[i].score << endl;
}
ofs.close();
// 读取文件stud.txt中的数据
ifstream ifs("stud.txt");
if (!ifs) {
cerr << "无法打开文件" << endl;
return 1;
}
for (int i = 0; i < MAX_STUDENTS; i++) {
ifs >> students[i].id >> students[i].name >> students[i].score;
}
ifs.close();
// 按照平均分排序
sort(students, students + MAX_STUDENTS, compare);
// 输出到屏幕和文件studsort.txt中
ofstream ofs_sort("studsort.txt");
if (!ofs_sort) {
cerr << "无法打开文件" << endl;
return 1;
}
cout << "排序后的结果:" << endl;
ofs_sort << "排序后的结果:" << endl;
for (int i = 0; i < MAX_STUDENTS; i++) {
cout << students[i].id << " " << students[i].name << " " << students[i].score << endl;
ofs_sort << students[i].id << " " << students[i].name << " " << students[i].score << endl;
}
ofs_sort.close();
return 0;
}
```
阅读全文