c++将学生成绩排序输入文件
时间: 2023-12-13 16:03:34 浏览: 30
假设你的输入文件中每行包含两个信息:学生姓名和其分数。你可以使用C++的STL库中的vector容器来存储每个学生的信息,然后使用sort函数对其进行排序,最后将排序结果输出到输出文件中。
以下是示例代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
struct Student {
std::string name;
int score;
};
bool compare(Student a, Student b) {
return a.score > b.score;
}
int main() {
std::ifstream input("input.txt"); // 打开输入文件
std::vector<Student> students; // 创建一个存储学生信息的vector
// 从输入文件中读取每个学生的信息
std::string name;
int score;
while (input >> name >> score) {
students.push_back({name, score});
}
// 使用sort函数对学生信息进行排序
std::sort(students.begin(), students.end(), compare);
// 将排序结果输出到输出文件中
std::ofstream output("output.txt");
for (auto student : students) {
output << student.name << " " << student.score << std::endl;
}
return 0;
}
```
在这个示例代码中,我们首先打开输入文件 `input.txt`,然后使用while循环逐行读取每个学生的信息,并将其存储到一个 `Student` 结构体中,并将其添加到一个vector中。接下来,我们使用sort函数对学生信息进行排序,这里我们使用一个自定义的compare函数来指定排序规则,即按照学生成绩从高到低排序。最后,我们打开输出文件 `output.txt`,并将排序结果逐行输出到文件中。