You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何跳过文本文件首行并按多条件排序学生记录?

问题1:跳过文本文件第一行读取

打开文件后直接调用一次getline读取第一行内容并丢弃即可,代码片段如下:

ifstream ifs("student-file.txt");
string skip_line;
// 读取第一行直接丢弃
getline(ifs, skip_line);

另外你原有代码中while(!ifs.eof())的写法存在逻辑问题,会多读入一次无效数据,建议将读取逻辑调整为读取成功再写入数组。

问题2:多条件联动排序

你当前排序逻辑只修改了firstname单个字段,才会出现三个字段不匹配的问题,排序时需要交换完整的studentRecord结构体对象,而非单个字段。多条件比较规则为:优先比较firstname,firstname相同时比较lastname,lastname也相同时比较grade。

这里提供调用标准库std::sort的实现方式,代码更简洁不易出错,需要额外引入<vector>和<algorithm>头文件。

完整修正代码

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
  
struct studentRecord{
    string lastname;
    string firstname;
    string grade;
};

// 自定义比较函数
bool compareStudent(const studentRecord& a, const studentRecord& b) {
    if (a.firstname != b.firstname) {
        return a.firstname < b.firstname;
    }
    if (a.lastname != b.lastname) {
        return a.lastname < b.lastname;
    }
    return a.grade < b.grade;
}
 
int main(){
    ifstream ifs("student-file.txt");
    if(ifs.fail()) {
        cout << "Error opening student records file" << endl;
        exit(1);
     }
    // 跳过第一行
    string skip_line;
    getline(ifs, skip_line);

    vector<studentRecord> records;
    string lastname, firstname, grade;
    // 修正读取逻辑
    while(ifs >> lastname >> firstname >> grade) {
        studentRecord s;
        s.lastname = lastname;
        s.firstname = firstname;
        s.grade = grade;
        records.push_back(s);
    }  

    // 多条件排序
    sort(records.begin(), records.end(), compareStudent);

    // 输出结果
    for (int k = 0; k < records.size(); k++) {
        cout << records[k].firstname << "\t" 
             << records[k].lastname << "\t" 
             << records[k].grade << endl;
    }
    return 0;
}

如果你需要保留原有的插入排序实现,只需要将排序逻辑中移动单个firstname的部分,改为移动整个studentRecord对象,同时调整比较条件即可。

内容的提问来源于stack exchange,提问作者peanut butter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:45:00