实验6 文件I/O与异常处理
一、实验任务1
源代码task1
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 }
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 }
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 }
运行结果截图

问题1:流操作与代码复用
观察 print() 与 save() 的实现,均在内部调用 write() :
(1) write() 的参数类型是 std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream 对象作为实参?
std::ostream 是 std::cout(ostream 类实例)和 std::ofstream(ostream 派生类)的基类,基类引用可以绑定到任意派生类对象(多态特性),因此 std::cout 和 std::ofstream 对象均能适配 std::ostream& 类型的参数要求。
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?
不需要改动。write () 仅依赖 std::ostream 接口,只要新设备的接口继承自 std::ostream 且兼容其调用规范,可直接传入 write (),体现了代码的复用性。
问题2:异常处理与捕获
在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
两处 throw 均为 throw std::runtime_error("fail to open " + filename):
load () 中:尝试打开指定文件(如 data.txt)失败时,输入流状态异常,抛出该异常;
save () 中:尝试创建 / 写入指定文件(如 ans.txt)失败时,输出流状态异常,抛出该异常。
(2)异常被谁捕获、做了哪些处理。
两处异常均被 app () 函数中的 try-catch 块捕获; 处理逻辑:通过 catch(const std::exception& e) 捕获异常后,调用 std::cerr << e.what() << '\n' 输出异常具体信息(如 “fail to open ./data.txt”),随后执行 return 退出 app () 函数,终止后续操作。
问题3:替代写法
函数 app 中 std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 参数cmp_by_solve 换成下面的lambda表达式是否可以?功能、性能、结果是否一致
[](const Contestant& a, const Contestant& b) {
return a.solved != b.solved ? a.solved > b.solved
: a.penalty < b.penalty;}
可以替换,且功能、性能、结果完全一致。
功能上:lambda 表达式完全复现了 cmp_by_solve 的逻辑 —— 先按解题数降序排序,解题数相同时按罚时升序排序;
性能上:lambda 表达式无函数调用的额外开销,与原函数实现效率一致;
结果上:排序规则未变,最终 contestants 的排序结果完全相同。
问题4:数据完整性与代码健壮性
把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。

运行结果问题:部分数据读取错误(如某参赛者的解题数 / 罚时被错误赋值),且后续多条数据记录缺失(如 Jennie、Tibby、Vermont 的数据未读取)。
原因分析:原 load () 函数采用简单的流式读取逻辑,输入流会自动忽略前导空白符;当遇到空白行 / 字段缺失行时,会错误读取下一行的有效数据填充当前字段(如将序号读为解题数、学号读为罚时);当读取到类型不匹配的数据(如期望 int 却读到 string)时,输入流进入 fail 状态,while 循环终止,后续数据无法读取。
(2)思考:如何修改函数 std::vector<Contestant> load(const std::string& filename) ,使其提示出错行号并跳过有问题的数据行,同时让程序继续执行?(选答*)
改用 std::getline 逐行读取文件,通过 std::istringstream 解析单行数据,维护行号变量定位错误行;空行 / 格式错误行仅输出警告并跳过,不终止程序执行,保证有效数据正常读取。
1 inline std::vector<Contestant> load(const std::string& filename) { 2 std::ifstream is(filename); 3 if (!is) throw std::runtime_error("fail to open " + filename); 4 5 std::string line; 6 std::getline(is, line); // 跳过标题行 7 std::vector<Contestant> v; 8 int line_num = 1; 9 10 while (std::getline(is, line)) { 11 line_num++; 12 if (line.empty()) { // 检测空行 13 std::cerr << "警告:第" << line_num << "行为空行,跳过\n"; 14 continue; 15 } 16 17 Contestant t; 18 int seq; 19 std::istringstream iss(line); 20 // 校验格式并处理 21 if (!(iss >> seq >> t.id >> t.name >> t.major >> t.solved >> t.penalty)) { 22 std::cerr << "错误:第" << line_num << "行格式错误,跳过\n"; 23 continue; 24 } 25 v.push_back(t); 26 } 27 return v; 28 }
二、实验任务2
源代码task2
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 };
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 };
1 #include <iostream> 2 #include <limits> 3 #include <string> 4 #include "stumgr.hpp" 5 6 const std::string in_file = "./data.txt"; 7 const std::string out_file = "./ans.txt"; 8 9 void menu() { 10 std::cout << "\n**********简易应用**********\n" 11 "1. 加载文件\n" 12 "2. 排序\n" 13 "3. 打印到屏幕\n" 14 "4. 保存到文件\n" 15 "5. 退出\n" 16 "请选择:"; 17 } 18 19 void app() { 20 StuMgr mgr; 21 22 while(true) { 23 menu(); 24 int choice; 25 std::cin >> choice; 26 27 try { 28 switch (choice) { 29 case 1: mgr.load(in_file); 30 std::cout << "加载成功\n"; break; 31 case 2: mgr.sort(); 32 std::cout << "排序已完成\n"; break; 33 case 3: mgr.print(); 34 std::cout << "打印已完成\n"; break; 35 case 4: mgr.save(out_file); 36 std::cout << "导出成功\n"; break; 37 case 5: return; 38 default: std::cout << "不合法输入\n"; 39 } 40 } 41 catch (const std::exception& e) { 42 std::cout << "Error: " << e.what() << '\n'; 43 } 44 } 45 } 46 47 int main() { 48 app(); 49 }
1 #include<iomanip> 2 #include "student.hpp" 3 #include <iostream> 4 5 // 获取专业 6 const std::string Student::get_major() const { 7 return major; 8 } 9 10 // 获取成绩 11 int Student::get_grade() const { 12 return grade; 13 } 14 15 // 重载输出操作符 << 16 std::ostream& operator<<(std::ostream& os, const Student& s) { 17 os << std::left 18 << std::setw(10) << s.id 19 << std::setw(15) << s.name 20 << std::setw(15) << s.major 21 << std::setw(10) << s.grade; 22 return os; 23 } 24 25 // 重载输入操作符 >> 26 std::istream& operator>>(std::istream& is, Student& s) { 27 is >> s.id >> s.name >> s.major >> s.grade; 28 return is; 29 }
1 #include "stumgr.hpp" 2 #include <fstream> 3 #include <algorithm> 4 #include <stdexcept> 5 6 // 加载数据文件 7 void StuMgr::load(const std::string& file) { 8 std::ifstream is(file); 9 if (!is) { 10 throw std::runtime_error("fail to open " + file); 11 } 12 13 // 清空旧数据 14 students.clear(); 15 std::string line; 16 if (!std::getline(is, line)) { 17 throw std::runtime_error("empty file: " + file); 18 } 19 Student s; 20 int line_num = 1; 21 while (is >> s) { 22 line_num++; 23 if (s.get_grade() < 0 || s.get_grade() > 100) { 24 throw std::runtime_error("invalid grade at line " + std::to_string(line_num)); 25 } 26 students.push_back(s); 27 } 28 if (is.fail() && !is.eof()) { 29 throw std::runtime_error("input format error near line " + std::to_string(line_num)); 30 } 31 } 32 33 // 排序 34 void StuMgr::sort() { 35 std::sort(students.begin(), students.end(), 36 [](const Student& a, const Student& b) { 37 if (a.get_major() != b.get_major()) { 38 return a.get_major() < b.get_major(); 39 } 40 return a.get_grade() > b.get_grade(); 41 }); 42 } 43 44 // 内部通用写入函数 45 void StuMgr::write(std::ostream& os) const { 46 47 for (const auto& s : students) { 48 os << s << '\n'; 49 } 50 } 51 52 // 打印 53 void StuMgr::print() const { 54 write(std::cout); 55 } 56 57 // 保存 58 void StuMgr::save(const std::string& file) const { 59 std::ofstream os(file); 60 if (!os) { 61 throw std::runtime_error("fail to open :" + file); 62 } 63 write(os); 64 }
运行结果截图



实验总结:
本次实验探究了C++流操作、异常处理、算法复用及代码健壮性。理解了ostream多态特性带来的代码复用优势,掌握了文件操作异常的捕获与处理方法,验证了lambda表达式与排序函数的等价性,同时发现简单流式读取的缺陷,认识到数据校验对提升代码健壮性的重要性。
浙公网安备 33010602011771号