任务6

任务1:

#pragma once
#include <iomanip>
#include <iostream>
#include <string>

struct Contestant {
    long   id;              // 学号
    std::string name;       // 姓名
    std::string major;      // 专业
    int    solved;          // 解题数
    int    penalty;         // 总罚时
};

// 重载<<
// 要求:姓名/专业里不含空白符
inline std::ostream& operator<<(std::ostream& out, const Contestant& c) {
    out << std::left;
    out << std::setw(15) << c.id
        << std::setw(15) << c.name
        << std::setw(15) << c.major
        << std::setw(10) << c.solved
        << std::setw(10) << c.penalty;

    return out;
}

// 重载>>
inline std::istream& operator>>(std::istream& in, Contestant& c) {
    in >> c.id >> c.name >> c.major >> c.solved >> c.penalty;

    return in;
}
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include "contestant.hpp"
#include "utils.hpp"

const std::string in_file = "./data.txt";
const std::string out_file = "./ans.txt";

void app() {
    std::vector<Contestant> contestants;

    try {
        contestants = load(in_file);                                      
        std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 
        print(contestants);      
        save(out_file, contestants);                         
    } catch (const std::exception& e) {
        std::cerr << e.what() << '\n';
        return;
    }
}

int main() {
    app();
}
#pragma once
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include "contestant.hpp"

// ACM 排序规则:先按解题数降序,再按罚时升序
inline bool cmp_by_solve(const Contestant& a, const Contestant& b) {
    if(a.solved != b.solved)
        return a.solved > b.solved;
    
    return a.penalty < b.penalty;
}

// 将结果写至任意输出流
inline void write(std::ostream& os, const std::vector<Contestant>& v) {
    for (const auto& x : v) 
        os << x << '\n';
}

// 将结果打印到屏幕
inline void print(const std::vector<Contestant>& v) {
    write(std::cout, v);
}

// 将结果保存到文件
inline void save(const std::string& filename, const std::vector<Contestant>& v) {
    std::ofstream os(filename);
    if (!os) 
        throw std::runtime_error("fail to open " + filename);

    write(os, v);
}

// 从文件读取信息(跳过标题行)
inline std::vector<Contestant> load(const std::string& filename) {
    std::ifstream is(filename);
    if (!is) 
        throw std::runtime_error("fail to open " + filename);

    std::string line;
    std::getline(is, line);          // 跳过标题

    std::vector<Contestant> v;
    Contestant t;
    int seq;
    while (is >> seq >> t) 
        v.push_back(t);
        
    return v;
}

运行结果截图:

屏幕截图 2025-12-23 223922

问题1:(1)因为 std::cout 的类型是 std::ostreamstd::ofstream 是继承自 std::ostream 的,它们都可以向上转型为 std::ostream&
write 函数只依赖于 std::ostream 的接口,所以任何输出流对象都可以传入。

(2)不需要改动 write() 函数

问题2:(1)if (!is) throw std::runtime_error("fail to open " + filename);和if (!os) throw std::runtime_error("fail to open " + filename);两处会被抛出

(2)异常被catch (const std::exception& e)捕获,做出处理是打印错误信息到 std::cerr,然后 app() 提前返回。

问题3:一致

问题4:如果文件中某一行缺少字段,operator>> 会读取失败,导致 while(is >> seq >> t) 循环提前结束,后面的数据可能读不到。

如果空白行在中间,operator>> 会读到空白行的列数不足,同样导致输入流失效,只加载部分数据。

屏幕上可能只输出部分数据,或者因为异常没被捕获而程序异常终止。

任务2:

#include "student.hpp"
#include <stdexcept>
#include <algorithm>

const std::string Student::get_major() const {
    return major;
}

int Student::get_grade() const {
    return grade;
}

std::ostream& operator<<(std::ostream& os, const Student& s) {
    os << s.id << "\t" << s.name << "\t" << s.major << "\t" << s.grade;
    return os;
}

std::istream& operator>>(std::istream& is, Student& s) {

    if (!(is >> s.id)) {
        is.setstate(std::ios::failbit);
        return is;
    }

    if (!(is >> s.name)) {
        is.setstate(std::ios::failbit);
        return is;
    }
  
    if (!(is >> s.major)) {
        is.setstate(std::ios::failbit);
        return is;
    }
    
    if (!(is >> s.grade)) {
        is.setstate(std::ios::failbit);
        return is;
    }
   
    if (s.grade < 0 || s.grade > 100) {
        throw std::runtime_error("成绩值不合法,应在0-100之间");
    }
    
    return is;
}
#pragma once

#include <iostream>
#include <string>

class Student {
public:
    Student() = default;
    ~Student() = default;
    
    const std::string get_major() const;
    int get_grade() const;

    friend std::ostream& operator<<(std::ostream& os, const Student& s);
    friend std::istream& operator>>(std::istream& is, Student& s);

private:
    int id;   
    std::string  name;
    std::string  major;
    int          grade;  // 0-100
};
#include "stumgr.hpp"
#include <fstream>
#include <algorithm>
#include <stdexcept>
#include <iostream>

void StuMgr::load(const std::string& file) {
    std::ifstream in(file);
    if (!in.is_open()) {
        throw std::runtime_error("cannot open file: " + file);
    }

    students.clear();

    std::string header;
    std::getline(in, header);

    Student s;
    while (in >> s) {
        students.push_back(s);
    }

    if (!in.eof() && in.fail()) {
        throw std::runtime_error("文件格式错误或数据不完整");
    }
    
    in.close();
}

void StuMgr::sort() {
    std::sort(students.begin(), students.end(), 
        [](const Student& a, const Student& b) {
            if (a.get_major() != b.get_major()) {
                return a.get_major() < b.get_major();
            }
            return a.get_grade() > b.get_grade(); 
        });
}

void StuMgr::write(std::ostream &os) const {
    if (students.empty()) {
        os << "(empty)\n";
        return;
    }

    os << "学号\t姓名\t专业\t成绩\n";

    for (const auto& s : students) {
        os << s << "\n";
    }
}

void StuMgr::print() const {
    write(std::cout);
}

void StuMgr::save(const std::string& file) const {
    std::ofstream out(file);
    if (!out.is_open()) {
        throw std::runtime_error("cannot open file: " + file);
    }
    
    write(out);
    out.close();
}
#pragma once
#include <string>
#include <vector>
#include "student.hpp"

class StuMgr {
public:
    void load(const std::string& file);  // 加载数据文件(空格分隔)
    void sort();                         // 排序: 按专业字典序升序、同专业分数降序
    void print() const;                  // 打印到屏幕
    void save(const std::string& file) const; // 保存到文件

private:
    void write(std::ostream &os) const;  // 把数据写到任意输出流

private:
    std::vector<Student> students;
};
#include <iostream>
#include <limits>
#include <string>
#include "stumgr.hpp"

const std::string in_file = "./data.txt";
const std::string out_file = "./ans.txt";

void menu() {
    std::cout << "\n**********简易应用**********\n"
                 "1. 加载文件\n"
                 "2. 排序\n"
                 "3. 打印到屏幕\n"
                 "4. 保存到文件\n"
                 "5. 退出\n"
                 "请选择:";
}

void app() {
    StuMgr mgr;

    while(true) {
        menu();
        int choice;
        std::cin >> choice;

        try {
            switch (choice) {
            case 1: mgr.load(in_file); 
                    std::cout << "加载成功\n"; break;
            case 2: mgr.sort(); 
                    std::cout << "排序已完成\n"; break;
            case 3: mgr.print(); 
                    std::cout << "打印已完成\n"; break;
            case 4: mgr.save(out_file); 
                    std::cout << "导出成功\n"; break;
            case 5: return;
            default: std::cout << "不合法输入\n";
            }
        }
        catch (const std::exception& e) {
            std::cout << "Error: " << e.what() << '\n';
        }
    }
}

int main() {
    app();
}

运行结果截图:

屏幕截图 2025-12-23 230651

 

posted @ 2025-12-23 23:09  封从想  阅读(4)  评论(0)    收藏  举报