实验6 文件I/O与异常处理
实验任务1
程序源代码如下:
contestant.hpp
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 inline std::ostream& operator<<(std::ostream& out, const Contestant& c) { 15 out << std::left; 16 out << std::setw(15) << c.id 17 << std::setw(15) << c.name 18 << std::setw(15) << c.major 19 << std::setw(10) << c.solved 20 << std::setw(10) << c.penalty; 21 22 return out; 23 } 24 25 inline std::istream& operator>>(std::istream& in, Contestant& c) { 26 in >> c.id >> c.name >> c.major >> c.solved >> c.penalty; 27 28 return in; 29 }
utils.hpp
1 #pragma once 2 #include <fstream> 3 #include <iostream> 4 #include <stdexcept> 5 #include <string> 6 #include <vector> 7 #include "contestant.hpp" 8 9 inline bool cmp_by_solve(const Contestant& a, const Contestant& b) { 10 if (a.solved != b.solved) 11 return a.solved > b.solved; 12 13 return a.penalty < b.penalty; 14 } 15 16 inline void write(std::ostream& os, const std::vector<Contestant>& v) { 17 for (const auto& x : v) 18 os << x << '\n'; 19 } 20 21 inline void print(const std::vector<Contestant>& v) { 22 write(std::cout, v); 23 } 24 25 inline void save(const std::string& filename, const std::vector<Contestant>& v) { 26 std::ofstream os(filename); 27 if (!os) 28 throw std::runtime_error("fail to open " + filename); 29 30 write(os, v); 31 } 32 33 inline std::vector<Contestant> load(const std::string& filename) { 34 std::ifstream is(filename); 35 if (!is) 36 throw std::runtime_error("fail to open " + filename); 37 38 std::string line; 39 std::getline(is, line); 40 41 std::vector<Contestant> v; 42 Contestant t; 43 int seq; 44 while (is >> seq >> t) 45 v.push_back(t); 46 47 return v; 48 }
task1.cpp
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 = "D:/Users/90654/Downloads/实验6部分代码及数据文件_gbk/实验6部分代码及数据文件_gbk/1/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 } 20 catch (const std::exception& e) { 21 std::cerr << e.what() << '\n'; 22 return; 23 } 24 } 25 26 int main() { 27 app(); 28 }
程序运行结果截图如下:

ans.txt文件截图如下:

问题1:观察 print() 与 save() 的实现,均在内部调用 write() :
(1) write() 的参数类型是 std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream 对象作为实参?
std::cout是std::ostream的实例,std::ofstream是std::ostream的派生类,基类引用形参是可以传入派生类作为实参的,故可同时接受两对象作为实参
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?
不需要,更改写入的设备地址即可。
问题2:在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
throw std::runtime_error("fail to open " + filename):当打不开输出文件时抛出异常
throw std::runtime_error("fail to open " + filename):当打不开输入文件时抛出异常
(2)异常被谁捕获、做了哪些处理。
被app()函数中的catch捕获,输出异常信息并终止程序运行
问题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表达式代替了com_by_solve函数;性能一致,结果也一致
问题4:把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。
运行结果截图如下:
出现问题有:罚时列出现学号;原来有十条数据,而只打印出了前七个数据
原因可能是:文件中存在空白行,序号7所在行的解题数和罚时数存在缺失
(2)思考:如何修改函数 std::vector<Contestant> load(const std::string& filename) ,使其提示出错行号并跳过有问题的数据行,同时让程序继续执行?
可以添加文件数据读取时的是否有效判断,并在读取文件数据的时候加上try-catch块去捕获异常信息,以便跳过有问题的数据行,让程序继续执行,具体实现可见实验任务2
实验任务2:
程序源代码如下:
student.hpp
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; 22 };
stumgr.hpp
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 };
student.cpp
1 #include "student.hpp" 2 #include <iomanip> 3 4 const std::string Student::get_major() const { 5 return major; 6 } 7 8 int Student::get_grade() const { 9 return grade; 10 } 11 12 std::ostream& operator<<(std::ostream& os, const Student& s) { 13 os << std::left; 14 os << std::setw(15) << s.id 15 << std::setw(15) << s.name 16 << std::setw(15) << s.major 17 << std::setw(15) << s.grade; 18 return os; 19 } 20 21 std::istream& operator>>(std::istream& is, Student& s) { 22 is >> s.id >> s.name >> s.major >> s.grade; 23 return is; 24 }
stumgr.cpp
1 #include "stumgr.hpp" 2 #include <fstream> 3 #include <algorithm> 4 5 void StuMgr::load(const std::string& file) { 6 std::ifstream is(file); 7 if (!is) { 8 throw std::runtime_error("文件无法打开" + file); 9 } 10 11 std::string line; 12 std::getline(is, line); 13 int count = 2; 14 15 while (std::getline(is, line)) { 16 Student s; 17 bool flag = true;
std::istringstream iss(line); 18 iss >> s; 19 20 try { 21 if (iss.fail()) { 22 throw std::invalid_argument("字段格式错误"); 23 } 24 25 if (s.get_grade() < 0 || s.get_grade() > 100) { 26 throw std::invalid_argument("成绩范围错误" ); 27 } 28 } 29 catch (const std::exception& e) { 30 std::cout << "第" << count << "行:" << e.what() << "\n"; 31 flag = false;
count++; 32 } 33 34 if (flag) { 35 students.push_back(s); 36 } 37 count++; 38 } 39 } 40 41 void StuMgr::sort() { 42 std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) { 43 return a.get_major() != b.get_major() ? a.get_major() < b.get_major() : a.get_grade() > b.get_grade(); 44 }); 45 } 46 47 void StuMgr::print() const { 48 write(std::cout); 49 } 50 51 void StuMgr::save(const std::string& file) const { 52 std::ofstream os(file); 53 if (!os) { 54 throw std::runtime_error("fail to open " + file); 55 } 56 write(os); 57 } 58 59 void StuMgr::write(std::ostream& os) const { 60 for (const auto& s : students) { 61 os << s << "\n"; 62 } 63 }
task2.cpp
1 #include <iostream> 2 #include <limits> 3 #include <string> 4 #include "stumgr.hpp" 5 6 const std::string in_file = "d:/Users/90654/Downloads/实验6部分代码及数据文件_gbk/实验6部分代码及数据文件_gbk/2/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 }
运行结果截图如下:


保存到文件ans.txt截图如下:

接下来替换data_bad.txt,运行结果截图如下:


更新后的ans.txt截图如下:

实验总结:
通过此次实验,我对文件的I/O操作更加熟悉,同时也认识到异常处理在企业级代码中的重要性,并尝试着写简单的异常处理来处理简单程序中可能发生的错误
浙公网安备 33010602011771号