实验六

实验任务一:

 1 #pragma once
 2 #include <iomanip>
 3 #include <iostream>
 4 #include <string>
 5 
 6 struct Contestant {
 7     long   id;              // 学号
 8     std::string name;       // 姓名
 9     std::string major;      // 专业
10     int    solved;          // 解题数
11     int    penalty;         // 总罚时
12 };
13 
14 // 重载<<
15 // 要求:姓名/专业里不含空白符
16 inline std::ostream& operator<<(std::ostream& out, const Contestant& c) {
17     out << std::left;
18     out << std::setw(15) << c.id
19         << std::setw(15) << c.name
20         << std::setw(15) << c.major
21         << std::setw(10) << c.solved
22         << std::setw(10) << c.penalty;
23 
24     return out;
25 }
26 
27 // 重载>>
28 inline std::istream& operator>>(std::istream& in, Contestant& c) {
29     in >> c.id >> c.name >> c.major >> c.solved >> c.penalty;
30 
31     return in;
32 }
contestant.hpp
 1 #pragma once
 2 #include <fstream>
 3 #include <iostream>
 4 #include <stdexcept>
 5 #include <string>
 6 #include <vector>
 7 #include "contestant.hpp"
 8 
 9 // ACM 排序规则:先按解题数降序,再按罚时升序
10 inline bool cmp_by_solve(const Contestant& a, const Contestant& b) {
11     if(a.solved != b.solved)
12         return a.solved > b.solved;
13     
14     return a.penalty < b.penalty;
15 }
16 
17 // 将结果写至任意输出流
18 inline void write(std::ostream& os, const std::vector<Contestant>& v) {
19     for (const auto& x : v) 
20         os << x << '\n';
21 }
22 
23 // 将结果打印到屏幕
24 inline void print(const std::vector<Contestant>& v) {
25     write(std::cout, v);
26 }
27 
28 // 将结果保存到文件
29 inline void save(const std::string& filename, const std::vector<Contestant>& v) {
30     std::ofstream os(filename);
31     if (!os) 
32         throw std::runtime_error("fail to open " + filename);
33 
34     write(os, v);
35 }
36 
37 // 从文件读取信息(跳过标题行)
38 inline std::vector<Contestant> load(const std::string& filename) {
39     std::ifstream is(filename);
40     if (!is) 
41         throw std::runtime_error("fail to open " + filename);
42 
43     std::string line;
44     std::getline(is, line);          // 跳过标题
45 
46     std::vector<Contestant> v;
47     Contestant t;
48     int seq;
49     while (is >> seq >> t) 
50         v.push_back(t);
51         
52     return v;
53 }
utils.hpp
 1 #include <algorithm>
 2 #include <iostream>
 3 #include <stdexcept>
 4 #include <vector>
 5 #include "contestant.hpp"
 6 #include "utils.hpp"
 7 
 8 const std::string in_file = "./data.txt";
 9 const std::string out_file = "./ans.txt";
10 
11 void app() {
12     std::vector<Contestant> contestants;
13 
14     try {
15         contestants = load(in_file);                                      
16         std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 
17         print(contestants);      
18         save(out_file, contestants);                         
19     } catch (const std::exception& e) {
20         std::cerr << e.what() << '\n';
21         return;
22     }
23 }
24 
25 int main() {
26     app();
27 }
task.cpp

运行截图:

image

 问题一:(1):std::cout和std::ofstream均为std::ostream派生类,基类引用兼容;

    (2):无需,接口一致就行。

问题二:(1):文件打开失败时抛出异常

(2):由app()的try-catch捕获,输出错误信息并退出。

问题三:(1):可以,功能、性能、结果均一致。

问题四:(1):当load()函数执行is >> seq >> t时,data_bad.txt第 7 行仅能提供 “序号 7、学号 204942076、姓名 Thomas、专业未来专业 6”4 个字段,后续读取 “解题数” 和 “罚时” 时无数据可用,流会设置failbit,但原load()函数未检查流状态,也未调用is.clear()清理,导致后续读取第 8 行时,流仍处于 “失败状态”,无法正确识别字段边界。

image

实验任务二:

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 class Student {
 7 public:
 8     Student() = default;
 9     ~Student() = default;
10     
11     const std::string get_major() const;
12     int get_grade() const;
13 
14     friend std::ostream& operator<<(std::ostream& os, const Student& s);
15     friend std::istream& operator>>(std::istream& is, Student& s);
16 
17 private:
18     int id;   
19     std::string  name;
20     std::string  major;
21     int          grade;  // 0-100
22 };
student.hpp
 1 #pragma once
 2 #include <string>
 3 #include <vector>
 4 #include "student.hpp"
 5 
 6 class StuMgr {
 7 public:
 8     void load(const std::string& file);  // 加载数据文件(空格分隔)
 9     void sort();                         // 排序: 按专业字典序升序、同专业分数降序
10     void print() const;                  // 打印到屏幕
11     void save(const std::string& file) const; // 保存到文件
12 
13 private:
14     void write(std::ostream &os) const;  // 把数据写到任意输出流
15 
16 private:
17     std::vector<Student> students;
18 };
stumgr.hpp
#include "student.hpp"
#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(12) << s.id       
        << std::setw(10) << s.name     
        << std::setw(12) << s.major    
        << std::setw(6) << 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 <fstream>  
#include <stdexcept> 
#include <algorithm> 
#include <iomanip>  
#include <sstream>   
#include <limits>    

void StuMgr::load(const std::string& file) {
    std::ifstream is(file);

    if (!is.is_open()) {
        throw std::runtime_error("cannot open file: " + file);
    }

    students.clear();  
    std::string line;
    std::getline(is, line);  
    int line_num = 1;       

    while (std::getline(is, line)) {
        line_num++;
        if (line.empty()) continue;  

        std::istringstream iss(line);
        Student s;
        
        if (iss >> s) {
            students.push_back(s);
        }
    }

    is.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 {
    if (students.empty()) {
        std::cout << "(empty)\n"; 
        return;
    }

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

    for (const auto& s : students) {
        std::cout << s << '\n';
    }
}

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

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

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

void StuMgr::write(std::ostream& os) const {
    for (const auto& s : students) {
        os << s << '\n'; 
    }
}
stumgr.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();
}
task2.cpp

运行截图:

image

 

image

 

posted @ 2025-12-21 21:09  yahuao  阅读(2)  评论(0)    收藏  举报