实验6

实验任务1

contestant.hpp

#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;
}

 

 utils.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;
}

 

task1.cpp

#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();
}#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();
}

 

运行结果

image

 

image

 问题1

(1)std::cout和std::ofstream都是继承自std::ostream的派生类

C++(4): std::ofstream的使用-CSDN博客

“std::cout”和“std::ostream”之间有什么关系? - 我爱学习网

(2)不需要改动write()

 

问题2

(1)无法打开文件(文件不存在或路径错误等)

(2)被task1.cpp的try-catch捕获

输出异常信息并终止程序

 

问题3

可以,功能、性能、结果一致

 

问题4

(1)

image

 序号7那一行缺项,解题数和总罚时分别读取了下一行的序号和学号

 

实验任务2

student.hpp
#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.cpp
#include "student.hpp"
#include <stdexcept>
#include <iomanip>

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 << std::left
       << std::setw(8) << s.id     
       << std::setw(10) << s.name  
       << std::setw(10) << s.major  
       << std::setw(6) << s.grade;  
    return os;
}

std::istream& operator>>(std::istream& is, Student& s) {
    std::ios::iostate state = is.rdstate();
    is.clear(); 

    is >> s.id >> s.name >> s.major >> s.grade;

    if (is.fail()) {
        is.setstate(state); 
        throw std::invalid_argument("字段缺失或格式错误");
    }

    if (s.grade < 0 || s.grade > 100) {
        throw std::out_of_range("成绩超出有效范围(0-100)");
    }

    return is;
}

 

stumgr.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.cpp
#include "stumgr.hpp"
#include "student.hpp"
#include <fstream>
#include <stdexcept>
#include <algorithm>
#include <iomanip>
#include <sstream>

void StuMgr::load(const std::string& file) {
    std::ifstream is(file);
    if (!is.is_open()) {
        throw std::runtime_error("无法打开文件: " + file);
    }

    students.clear();
    std::string line;
    int line_num = 0;

    std::getline(is, line);
    line_num++;

    while (std::getline(is, line)) {
        line_num++;
        std::istringstream iss(line);
        Student s;

        try {
            iss >> s;
            students.push_back(s); 
        } catch (const std::exception& e) {
            std::cerr << "[Warning] 第" << line_num << "行: " << e.what() << ",已跳过\n";
        }
    }

    is.close();
    if (students.empty()) {
        std::cerr << "[Warning] 未加载到有效学生数据\n";
    }
}

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();
        } else {
            return a.get_grade() > b.get_grade();
        }
    });
}

void StuMgr::print() const {
    std::cout << std::left
              << std::setw(8) << "学号"
              << std::setw(10) << "姓名"
              << std::setw(10) << "专业"
              << std::setw(6) << "成绩" << "\n";
    std::cout << std::string(34, '-') << "\n";

    write(std::cout);
}

void StuMgr::save(const std::string& file) const {
    std::ofstream os(file);
    if (!os.is_open()) {
        throw std::runtime_error("无法创建文件: " + file);
    }

    os << std::left
       << std::setw(8) << "学号"
       << std::setw(10) << "姓名"
       << std::setw(10) << "专业"
       << std::setw(6) << "成绩" << "\n";
    os << std::string(34, '-') << "\n";

    write(os);
    os.close();
}

void StuMgr::write(std::ostream& os) const {
    for (const auto& s : students) {
        os << s << "\n";
    }
}

 

task2.cpp
#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();
}

 运行结果

image

 

image

 

image

 

image

 

 

posted @ 2025-12-22 20:33  kdd184  阅读(3)  评论(0)    收藏  举报