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

问题1:
答:
(1)write () 的参数类型是std::ostream&,能同时接受std::cout和std::ofstream对象作为实参,是因为std::cout是std::ostream类的实例,而std::ofstream是std::ostream的派生类。C++ 中基类引用可以绑定到派生类对象,实现了多态特性,因此 write () 函数可以统一处理所有std::ostream及其派生类的输出流对象。
(2)不需要改动 write () 函数。只要新设备的输出流类继承自std::ostream并实现了std::ostream的接口,write () 函数就能直接复用,体现了代码的可扩展性和复用性。
问题2:
答:
(1)两处 throw 语句分别在 save () 和 load () 函数中:
save () 函数中,当打开输出文件失败(!os为真)时,抛出std::runtime_error异常,异常信息为 “fail to open + 文件名”。
load () 函数中,当打开输入文件失败(!is为真)时,抛出std::runtime_error异常,异常信息为 “fail to open + 文件名”。
(2)异常由 app () 函数中的 try-catch 块捕获。捕获后,通过std::cerr输出异常信息,程序返回,避免程序崩溃,保证了程序的健壮性。
问题3:
答:
可以替换,功能、性能、结果完全一致。
功能上:lambda 表达式实现的逻辑与 cmp_by_solve 函数完全相同,均为先按解题数降序,解题数相同时按罚时升序排序。
性能上:两者均为直接访问对象成员进行比较,无额外开销,性能一致。
结果上:排序逻辑一致,输入相同数据时输出结果完全相同。lambda 表达式更简洁,无需单独定义函数,适合短期使用的简单比较逻辑。
问题4:
答:
(1)运行结果问题:程序可能出现数据读取不完整、程序崩溃或输出乱码。
原因:data_bad.txt 中存在空白行、字段缺失、数据格式错误等问题。
原 load () 函数通过is >> seq >> t读取数据,当遇到非法格式或缺失字段时,输入流会进入错误状态,后续读取操作失效,导致数据读取不完整;若错误数据导致内存访问异常,会直接造成程序崩溃。

(2)修改后的 load () 函数:
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); int line_num = 2; std::vector<Contestant> v; Contestant t; int seq; while (std::getline(is, line)) { std::istringstream iss(line); if (iss >> seq >> t.id >> t.name >> t.major >> t.solved >> t.penalty) { v.push_back(t); } else { std::cerr << "[Warning] line " << line_num << " format error, skipped\n"; } line_num++; } is.close(); return v; }
实验任务2
源代码:
#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 };
#include "student.hpp" #include <iomanip> // 用于格式化输出 #include <sstream> // 用于数据解析 #include <stdexcept> // 用于抛出成绩有效性异常 // 实现get_major:返回专业(供排序使用) const std::string Student::get_major() const { return major; } // 实现get_grade:返回成绩(供排序使用) int Student::get_grade() const { return grade; } // 重载<<:格式化输出学员信息(左对齐,固定宽度) std::ostream& operator<<(std::ostream& os, const Student& s) { os << std::left; os << std::setw(10) << s.id // 学号占10字符 << std::setw(10) << s.name // 姓名占10字符 << std::setw(10) << s.major // 专业占10字符 << std::setw(10) << s.grade;// 成绩占10字符 return os; } // 重载>>:读取学员信息+数据有效性校验 std::istream& operator>>(std::istream& is, Student& s) { // 临时变量存储读取结果(避免直接污染Student对象) int temp_id; std::string temp_name, temp_major; int temp_grade; // 按“学号-姓名-专业-成绩”顺序读取(失败则设置流错误状态) if (!(is >> temp_id >> temp_name >> temp_major >> temp_grade)) { is.setstate(std::ios::failbit); // 标记流为失败状态 return is; } // 成绩有效性校验(0-100范围) if (temp_grade < 0 || temp_grade > 100) { throw std::runtime_error("grade out of range (0-100): " + std::to_string(temp_grade)); } // 校验通过,赋值给Student对象 s.id = temp_id; s.name = temp_name; s.major = temp_major; s.grade = temp_grade; return is; }
#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 <stdexcept> #include <algorithm> #include <iostream> #include <sstream> // 用于逐行解析文件 // 加载文件:逐行读取+异常处理+脏数据跳过 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(); // 清空已有数据(避免重复加载) Student s; std::string line; int line_num = 1; // 记录行号(用于定位错误) // 逐行读取文件(处理空白行与脏数据) while (std::getline(is, line)) { line_num++; // 行号自增(标题行之后开始计数) // 跳过空白行(避免无意义解析) if (line.empty()) { continue; } // 将行内容转为字符串流,便于解析 std::istringstream iss(line); try { // 尝试解析当前行(调用Student重载的>>) if (iss >> s) { students.push_back(s); // 解析成功,添加到列表 } else { // 解析失败(字段缺失/格式错误),输出警告 std::cerr << "[Warning] line " << line_num << " format error, skipped: " << line << std::endl; } } catch (const std::exception& e) { // 捕获“成绩超出范围”异常,输出警告 std::cerr << "[Warning] line " << line_num << " invalid data, skipped: " << e.what() << " (content: " << line << ")" << std::endl; } } is.close(); // 关闭文件(释放资源) } // 排序:按“专业字典序升序→同专业成绩降序” void StuMgr::sort() { std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { // 第一步:按专业字典序比较(升序,如Acting < Music) if (a.get_major() != b.get_major()) { return a.get_major() < b.get_major(); } // 第二步:同专业按成绩降序(成绩高的排前) return a.get_grade() > b.get_grade(); } ); } // 打印到屏幕:调用write,输出流为std::cout void StuMgr::print() const { write(std::cout); } // 保存到文件:打开失败时抛出异常 void StuMgr::save(const std::string& file) const { std::ofstream os(file); // 创建文件输出流 if (!os.is_open()) { // 检查文件是否成功打开 throw std::runtime_error("cannot open file for writing: " + file); } write(os); // 调用write写入文件 os.close(); // 关闭文件 } // 私有通用写函数:支持任意ostream流(控制台/文件) void StuMgr::write(std::ostream& os) const { for (const auto& s : students) { os << s << std::endl; // 调用Student重载的<<输出单个学员 } }
#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(); }
运行结果截图:


浙公网安备 33010602011771号