如何使用getline()提取每行第三个字段完成GPA降序排序
实现思路
- 先定义结构体存储每行的ID、姓名、GPA三个字段信息
- 将所有行数据读取后存入vector容器暂存
- 自定义排序规则对vector按GPA降序排序
- 将排序后的数据逐行写入输出文件
完整代码
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <iomanip> using namespace std; // 定义结构体存储每行学生数据 struct Student { string id; string name; double gpa; }; int main() { ifstream inputfile("input.txt"); ofstream outputfile("output.txt"); if (inputfile.fail()) { cout << "Cannot open inputfile" << endl; return 1; } if (outputfile.fail()) { cout << "Cannot open outputfile" << endl; return 1; } vector<Student> students; if (inputfile.is_open()) { string line; while (getline(inputfile, line)) { stringstream ss(line); Student stu; string gpa_str; // 按制表符拆分三个字段 getline(ss, stu.id, '\t'); getline(ss, stu.name, '\t'); getline(ss, gpa_str, '\t'); stu.gpa = stod(gpa_str); students.push_back(stu); } } inputfile.close(); // 按GPA降序排序 sort(students.begin(), students.end(), [](const Student& a, const Student& b) { return a.gpa > b.gpa; }); // 写入输出文件,统一保留两位小数 outputfile << fixed << setprecision(2); for (const auto& stu : students) { outputfile << stu.id << "\t" << stu.name << "\t" << stu.gpa << endl; } outputfile.close(); return 0; }
输出结果示例
排序后生成的output.txt内容如下:
20210003 Royce 4.32 20210001 Bill 3.61 20210002 Joe 3.21 20210004 Lucy 2.21
内容的提问来源于stack exchange,提问作者Royce
相关产品推荐
相关产品推荐

