实验6 文件I/O与异常处理
实验任务1
代码
c++
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 #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;utild 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 #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 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
序号 学号 姓名 专业 解题数(道) 总罚时(分钟) 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
运行测试截图

问题回答
问题1:流操作与代码复用
观察 print() 与 save() 的实现,均在内部调用 write() :
(1) write() 的参数类型是 std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream 对象作
为实参?
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?
1)因为std::ostream&使用了C++的多态性和继承机制,std::cout就是std::ostream的对象,而std::ofstream是std::ostream的派生类,其引用可以绑定到基类的引用上。
2)不需要,write()仅依赖于ostream接口。
问题2:异常处理与捕获
在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
(2)异常被谁捕获、做了哪些处理。
1)


打开文件失败时会抛出异常
2)异常被app()函数 中的catch捕获,会输出错误提示("fail to open " + filename),并终止函数运行,退出函数。
问题3:替代写法
函数 app 中 std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 参数 cmp_by_solve 换成下面的lambda表达式是否可以?功能、性能、结果是否一致?
可以。功能、性能、结果基本一致,lambda更容易被编译器内联优化,性能更好。

问题4:数据完整性与代码健壮性
把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。
(2)思考:如何修改函数 std::vector load(const std::string& filename) ,使其提示出 错行号并跳过有问题的数据行,同时让程序继续执行?(选答*)
1)

问题:Thomas的解题数和总罚时信息有误;Jennie、Tibby和Vermont信息缺失。
原因:文件data_bad.txt文件中Thomas的解题数和总罚时信息缺失,使得读取该部分信息时直接跳转到下一行读取了Jennie的序号和学号信息,同时while循环也被终止,导致后面三人信息缺失。
2)
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; int count = 2; while (std::getline(is, line)) { // 检查是否为空行或全空白 bool blank = true; for (char c : line) { if (!std::isspace(c)) { blank = false; break; } } if (blank) { std::cerr << "[Warning]: 第" << count << "行数据为空或全空白!已跳过!" << std::endl; count++; continue; } std::istringstream iss(line); // ? 关键修复:全部使用 !(iss >> x),而不是 !(x) if (!(iss >> seq) || !(iss >> t.id) || !(iss >> t.name) || !(iss >> t.major) || !(iss >> t.solved) || !(iss >> t.penalty)) { std::cerr << "[Warning]: 第" << count << "行数据有误!已跳过!" << std::endl; } else { v.push_back(t); } count++; // ? 加上分号 } return v; }

实验任务2
代码
c++
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 return 0; 50 }
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 std::vector<Student> students; 16 };
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 #include "stumgr.hpp" 2 #include <fstream> 3 #include <sstream> 4 #include <iostream> 5 #include <algorithm> 6 #include <stdexcept> 7 8 void StuMgr::load(const std::string& file) { 9 std::ifstream is(file); 10 if (!is) { 11 throw std::runtime_error("无法打开文件: " + file); 12 } 13 14 students.clear(); 15 16 17 std::string header; 18 std::getline(is, header); 19 20 Student s; 21 std::string line; 22 int line_no = 2; 23 24 while (std::getline(is, line)) { 25 26 bool blank = true; 27 for (char c : line) { 28 if (!std::isspace(c)) { 29 blank = false; 30 break; 31 } 32 } 33 if (blank) continue; 34 35 std::istringstream iss(line); 36 if (!(iss >> s)) { 37 std::cerr << "[警告] 第" << line_no << "行格式错误,已跳过\n"; 38 } else if (s.get_grade() < 0 || s.get_grade() > 100) { 39 std::cerr << "[警告] 第" << line_no << "行成绩超出范围 [0,100]: " 40 << s.get_grade() << ",已跳过\n"; 41 } else { 42 students.push_back(s); 43 } 44 line_no++; 45 } 46 47 48 if (students.empty()) { 49 throw std::runtime_error("未找到有效学生数据"); 50 } 51 } 52 53 void StuMgr::sort() { 54 if (students.empty()) { 55 std::cout << "\n(empty)\n"; 56 return; 57 } 58 59 std::sort(students.begin(), students.end(), 60 [](const Student& a, const Student& b) { 61 if (a.get_major() != b.get_major()) 62 return a.get_major() < b.get_major(); 63 return a.get_grade() > b.get_grade(); 64 }); 65 } 66 67 void StuMgr::print() const { 68 if (students.empty()) { 69 std::cout << "\n(empty)\n"; 70 return; 71 } 72 73 std::cout << "\n学号\t姓名\t专业\t成绩\n"; 74 std::cout << "----------------------------\n"; 75 for (const auto& s : students) { 76 std::cout << s << '\n'; 77 } 78 std::cout << "----------------------------\n"; 79 } 80 81 void StuMgr::save(const std::string& file) const { 82 if (students.empty()) { 83 throw std::runtime_error("无数据可保存"); 84 } 85 86 std::ofstream os(file); 87 if (!os) { 88 throw std::runtime_error("无法创建文件: " + file); 89 } 90 write(os); 91 } 92 93 void StuMgr::write(std::ostream& os) const { 94 os << "学号\t姓名\t专业\t成绩\n"; 95 for (const auto& s : students) { 96 os << s << '\n'; 97 } 98 }
1 #include "student.hpp" 2 3 const std::string Student::get_major() const { 4 return major; 5 } 6 7 int Student::get_grade() const { 8 return grade; 9 } 10 11 std::ostream& operator<<(std::ostream& os, const Student& s) { 12 os << s.id << "\t" << s.name << "\t" << s.major << "\t" << s.grade; 13 return os; 14 } 15 16 std::istream& operator>>(std::istream& in, Student& s) { 17 in >> s.id >> s.name >> s.major >> s.grade; 18 return in; 19 }
运行测试截图
文件可正常打开且数据无误时:



文件无法打开时:

文件数据有误时:




浙公网安备 33010602011771号