实验6 文件I/O与异常处理
Task1
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;
}
#include <algorithm> #include <iostream> #include <stdexcept> #include <vector> #include "contestant.hpp" #include "utils.hpp" const std::string in_file = "./data_bad.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(); }
#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; }
2.运行截图:

3.问题回答:
问题1:流操作与代码复用
观察 print() 与 save() 的实现,均在内部调用 write() :
(1) write() 的参数类型是 std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream 对象作为实参?
答:因为 std::cout 是 std::ostream 类型的对象, std::ofstream又是std::ostream是派生类,所以它们都符合 std::ostream& 的接口要求。
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?
答:不需要改动 ,只要新的设备提供了兼容 std::ostream 的接口,就可以直接传入 write()。
问题2:异常处理与捕获
在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
答:两处throw分别在load()和save()中;
load() 中:当尝试打开 data.txt 失败时,!is 条件成立,抛出异常。
save() 中:当尝试创建或写入 ans.txt 失败时,!os 成立,抛出异常。
(2)异常被谁捕获、做了哪些处理。
答:这两个异常都在 app() 函数的 try-catch 块中被捕获。catch(const std::exception& e) 捕获所有标准异常,通过 e.what() 输出错误信息( "fail to open ./data.txt"),然后函数返回,程序结束。
问题3:替代写法
函数 app 中 std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 参数cmp_by_solve 换成下面的lambda表达式是否可以?功能、性能、结果是否一致
1 [](const Contestant& a, const Contestant& b) {
2 return a.solved != b.solved ? a.solved > b.solved
3 : a.penalty < b.penalty;}
答:可以,是一致的,因为lambda 完全实现了原函数 cmp_by_solve 的逻辑:先按解题数降序,再按罚时升序。
问题4:数据完整性与代码健壮性
把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。
答:数据部分缺失,当前 load() 函数使用了简单循环:一旦出现空白行或者数据类型不匹配之类的就会导致is >> t 失败,流入 fail 状态,后续读取全部被跳过。
(2)思考:如何修改函数 std::vector<Contestant> load(const std::string& filename) ,使其提示出
错行号并跳过有问题的数据行,同时让程序继续执行?(选答*)
Task2:
1.源代码:
#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
};
#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 <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();
}
#include<iomanip>
#include "student.hpp"
#include <iostream>
// 获取专业
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(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;
}
#include "stumgr.hpp"
#include <fstream>
#include <algorithm>
#include <stdexcept>
// 加载数据文件
void StuMgr::load(const std::string& file) {
std::ifstream is(file);
if (!is) {
throw std::runtime_error("fail to open " + file);
}
// 清空旧数据
students.clear();
std::string line;
// 跳过第一行
if (!std::getline(is, line)) {
throw std::runtime_error("empty file: " + file);
}
Student s;
int line_num = 1; // 记录行号
while (is >> s) {
line_num++;
// 验证成绩合法性(0-100)
if (s.get_grade() < 0 || s.get_grade() > 100) {
throw std::runtime_error("invalid grade at line " + std::to_string(line_num));
}
students.push_back(s);
}
if (is.fail() && !is.eof()) {
throw std::runtime_error("input format error near line " + std::to_string(line_num));
}
}
// 排序
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::write(std::ostream& os) const {
for (const auto& s : students) {
os << s << '\n';
}
}
// 打印
void StuMgr::print() const {
write(std::cout);
}
// 保存
void StuMgr::save(const std::string& file) const {
std::ofstream os(file);
if (!os) {
throw std::runtime_error("fail to open :" + file);
}
write(os);
}
2.运行截图:

ans.txt:



浙公网安备 33010602011771号