OOP实验六

实验任务一

源代码:

#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();
}
task1.cpp
#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;
}
contestant.hpp
#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;
}
utils.hpp
序号    学号        姓名        专业        解题数(道)    总罚时(分钟)
1    204942005    Jeny        未来专业1        4        210        
2    204942302    Alex           未来专业2        3        180
3    204942059    Bob        未来专业2        5        350                 
4    204942111    Hellen        未来专业3        2        90     
5    204942017    chappie        未来专业4        4        260     
6    204942075    Shaw        未来专业5        3        150        
7    204942076    Thomas        未来专业6        6        420      
8    204942078    Jennie        未来专业7        1        30          
9    204942079    Tibby        未来专业7        3        200        
10    204942080    Vermont        未来专业8        5        310    
data.txt
序号    学号        姓名        专业        解题数(道)    总罚时(分钟)
1    204942005    Jeny        未来专业1        4        210        
2    204942302    Alex           未来专业2        3        180

3    204942059    Bob        未来专业2        5        350                 
4    204942111    Hellen        未来专业3        2        90     
5    204942017    chappie        未来专业4        4        260     
6    204942075    Shaw        未来专业5        3        150        
7    204942076    Thomas        未来专业6              
8    204942078    Jennie        未来专业7        1        30          
9    204942079    Tibby        未来专业7        3        200        
10    204942080    Vermont        未来专业8        5        310    
data_bad.txt

运行结果:

屏幕截图 2025-12-17 090317

问题:

Q1:

  (1)因为std::cout和std::ofstream都是std::ostream的派生类,通过多态性,基类引用可以绑定到派生类对象。

  (2)不需要。任何提供std::ostream接口的设备对象均可作为实参传入,write函数无需修改。

Q2:代码中两处throw分别位于load和save函数。

  (1)load函数在打开输入文件失败时抛出异常;save函数在打开输出文件失败时抛出异常。

  (2)异常在app函数的try-catch块中被捕获,通过e.what()输出错误信息到标准错误流,然后函数返回。

Q3:可以替换。该lambda表达式与cmp_by_solve函数的比较逻辑完全一致,功能、性能和排序结果均相同。

Q4:运行结果会提前终止,只输出部分数据。原因是当读取到第7行不完整数据时,输入流进入错误状态,导致循环终止,后续所有正确数据均未被读取。

(运行结果如下)

屏幕截图 2025-12-17 091417

 

 

实验任务二

源代码:

#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();
}
task2.cpp
#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
};
student.hpp
#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;
};
stumgr.hpp
#include "student.hpp"
#include <string>
#include <sstream>

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) {
    is >> s.id >> s.name >> s.major >> s.grade;
    return is;
}
student.cpp
#include "stumgr.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdexcept>

void StuMgr::load(const std::string& file) {
    std::ifstream infile(file);
    if (!infile.is_open()) {
        throw std::runtime_error("cannot open file: " + file);
    }
    
    students.clear();
    
    std::string header;
    std::getline(infile, header);
    Student stu;
    while (infile >> stu) {
        students.push_back(stu);
    }
    
    infile.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::print() const {
    std::cout << "学号\t姓名\t专业\t成绩\n";
    for (const auto& stu : students) {
        std::cout << stu << std::endl;
    }
}

void StuMgr::save(const std::string& file) const {
    std::ofstream outfile(file);
    if (!outfile.is_open()) {
        throw std::runtime_error("cannot open file: " + file);
    }
    
    write(outfile);
    outfile.close();
}

void StuMgr::write(std::ostream &os) const {
    os << "学号\t姓名\t专业\t成绩\n";
    for (const auto& stu : students) {
        os << stu << std::endl;
    }
}
stumgr.cpp

运行结果:

屏幕截图 2025-12-23 154547

 

posted @ 2025-12-23 15:50  周心岚  阅读(2)  评论(0)    收藏  举报