实验六
实验任务一:
#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 #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 } task1.cpp
运行结果为:

问题一:
(1)std::cout 是 std::ostream 类型的标准输出流对象,std::ofstream 是文件输出流类,它继承自 std::ostream。由于 C++ 的多态特性,std::ofstream 对象可以向上转型为基类 std::ostream& 引用,因此 write() 函数能够同时接受这两种不同类型的对象作为实参。这就是面向对象编程中的 "is-a" 关系:文件输出流是一种输出流。
(2)如果要把结果写到其他也提供 std::ostream 接口的设备(如字符串流 std::ostringstream、网络流等),不需要改动 write() 函数。这正是代码复用的优势所在——通过设计接收基类引用的通用接口,任何派生自 std::ostream 的输出流对象都可以直接使用该函数,体现了面向对象设计的开闭原则(对扩展开放,对修改关闭)。
问题二:
(1)两处 throw 语句均在文件打开失败时抛出异常:第一处在 save() 函数中:当创建 std::ofstream 对象打开输出文件失败时;第二处在 load() 函数中:当创建 std::ifstream 对象打开输入文件失败时
(2)异常在 app() 函数中被 try-catch 块捕获。具体处理方式是:捕获到任何 std::exception 或其派生类的异常后,将异常信息(通过 e.what() 获取)输出到标准错误流 std::cerr,然后函数直接返回,终止程序继续执行。这种处理方式既向用户报告了错误(文件打开失败的具体原因),又避免了程序在文件不可用的情况下继续运行导致更严重的错误。
问题三:将 `cmp_by_solve` 替换为给出的 lambda 表达式完全可行,功能、性能和结果都完全一致。该 lambda 表达式与原始 `cmp_by_solve` 函数具有完全相同的逻辑:首先比较解题数,如果不等则按解题数降序排列(`a.solved > b.solved` 返回 `true` 时 `a` 排在 `b` 前面),如果解题数相等则按罚时升序排列(`a.penalty < b.penalty` 返回 `true` 时 `a` 排在 `b` 前面)。由于 lambda 表达式在编译期会被内联优化,性能上不会有任何损失,且排序结果也完全相同。这种写法更紧凑,特别适合在只使用一次的比较场景中直接内联定义,减少代码跳转和提高可读性。
问题四:

(1)将 `in_file` 改为 `"./data_bad.txt"` 后,如果文件内含空白行或字段缺失,程序可能会**正常编译但运行时出现不可预知的行为或崩溃。具体问题包括:读取到空白行时,`is >> seq >> t` 会失败但不会抛出异常,导致循环条件判断错误;字段缺失会导致 `operator>>` 无法正确读取所有数据,流状态变为失败,后续读取全部终止。程序不会直接报错,但可能生成不完整或错误的排序结果**,甚至可能输出空结果,且用户无法得知数据读取已失败。这是因为当前代码缺乏对读取失败的检查和异常处理,`load` 函数只检查文件能否打开,未验证数据读取的完整性,体现了代码健壮性的不足。
实验任务二:
#pragma once #include <iostream> #include <string> class Student { public: Student() = default; ~Student() = default; const std::string& get_major() const { return major; } int get_grade() const { return grade; } friend std::ostream& operator<<(std::ostream& os, const Student& s); friend std::istream& operator>>(std::istream& is, Student& s); // 添加比较运算符重载 bool operator<(const Student& other) const; private: int id; std::string name; std::string major; int grade; // 0-100 };
#include "student.hpp" #include <iomanip> std::ostream& operator<<(std::ostream& os, const Student& s) { os << std::left; os << std::setw(10) << s.id << std::setw(15) << s.name << std::setw(15) << s.major << std::setw(10) << s.grade; return os; } std::istream& operator>>(std::istream& is, Student& s) { is >> s.id >> s.name >> s.major >> s.grade; return is; } bool Student::operator<(const Student& other) const { if (major != other.major) return major < other.major; return grade > other.grade; // 同专业按成绩降序 }
#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 "stumgr.hpp" #include <fstream> #include <algorithm> #include <stdexcept> void StuMgr::load(const std::string& file) { std::ifstream ifs(file); if (!ifs) { throw std::runtime_error("Error: cannot open file: " + file); } students.clear(); std::string line; std::getline(ifs, line); // 跳过标题行 Student s; int seq; while (ifs >> seq >> s) { students.push_back(s); } } void StuMgr::sort() { if (students.empty()) { std::cout << "Empty\n"; return; } std::sort(students.begin(), students.end()); std::cout << "排序已完成\n"; } void StuMgr::write(std::ostream& os) const { os << std::left; os << std::setw(10) << "学号" << std::setw(15) << "姓名" << std::setw(15) << "专业" << std::setw(10) << "成绩" << "\n"; for (const auto& s : students) { os << s << "\n"; } } void StuMgr::print() const { if (students.empty()) { std::cout << "Empty\n"; return; } write(std::cout); } void StuMgr::save(const std::string& file) const { if (students.empty()) { std::cout << "Empty\n"; return; } std::ofstream ofs(file); if (!ofs) { throw std::runtime_error("Error: cannot open file: " + file); } write(ofs); }
#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; // 清除输入缓冲区 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); try { switch (choice) { case 1: mgr.load(in_file); std::cout << "文件加载成功\n"; break; case 2: mgr.sort(); break; case 3: mgr.print(); break; case 4: mgr.save(out_file); std::cout << "文件保存成功: " << out_file << "\n"; break; case 5: std::cout << "程序退出\n"; return; default: std::cout << "无效选择,请重新输入\n"; break; } } catch (const std::exception& e) { std::cerr << e.what() << "\n"; } } } int main() { app(); return 0; }
运行结果为:


浙公网安备 33010602011771号