实验6 文件I/O与异常处理

实验6

实验任务1

源代码

 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 }
contestant.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 // 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 }
utils.hpp
 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     }
20     catch (const std::exception& e) {
21         std::cerr << e.what() << '\n';
22         return;
23     }
24 }
25 
26 int main() {
27     app();
28 }
task1.cpp

实验结果

image

问题解答

问题1:流操作与代码复用
观察 print() 与 save() 的实现,均在内部调用 write() :
(1) write() 的参数类型是 std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream 对象作为实参?
ostream是所有输出流的基类,cout是ostream的一个对象实例,ofstream是ostream的一个派生类,派生类对象可以隐式转化为基类引用,可以作为实参传入。
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?

不需要提供,因为所有提供ostream接口的设备本质上都是ostream的派生类,可以直接复用write()。

问题2:异常处理与捕获
在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
1 if (!os)
2    throw std::runtime_error("fail to open " + filename);

当调用sava()函数打开输出文件失败时。

if (!is)
    throw std::runtime_error("fail to open " + filename);

当调用load()函数打开输入文件失败时。

(2)异常被谁捕获、做了哪些处理。

捕获:

 catch (const std::exception& e) {
     std::cerr << e.what() << '\n';
     return;
 }

处理:先捕获所有std::exception及其派生类异常,然后通过e.what()输出异常信息到标准错误流std::cerr,然后函数直接返回,终止后续的操作。

问题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;}

可以代替,功能、性能和结果是一致的.

问题4:数据完整性与代码健壮性
把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。

image

输出结果 Thomas缺少了总罚时和解题数的数据和Vermont整行的数据,因此产生了数据录入的错位,产生了“204942078”的错误数据,并且因为录入了空字符,导致了Vermont的数据缺失。

(2)思考:如何修改函数 std::vector<Contestant> load(const std::string& filename) ,使其提示出错行号并跳过有问题的数据行,同时让程序继续执行?(选答*)
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 line_num = 2;               
    
    while (true) {
        is >> seq >> t;
        if (is) {
            v.push_back(t);
            line_num++;
        } else {
            if (is.eof()) {
                break; 
            } else {
                std::cerr << "Warning: 第" << line_num << "行数据格式错误,已跳过" << std::endl;
                is.clear();
                std::getline(is, line);
                line_num++;
            }
        }
    }
    return v;
}

 

先增加line_num基类数据行号,然后使用while(true)循环代替原while(is>>seq>>t),当读取失败时,由is.eof()判断

是文件数据错误还是文件结束,当产生数据错误时,会输出错误行号并且清除输入流错误状态,并跳过当前行,执行下一行的输出。

 

实验任务2

 源代码

 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 };
student.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 };
stumgr.hpp
 1 #include "student.hpp"
 2 #include <stdexcept>
 3 #include <string>
 4 
 5 const std::string Student::get_major() const {
 6     return major;
 7 }
 8 
 9 int Student::get_grade() const {
10     return grade;
11 }
12 
13 std::ostream& operator<<(std::ostream& os, const Student& s) {
14     os << s.id << '\t' << s.name << '\t' << s.major << '\t' << s.grade;
15     return os;
16 }
17 
18 std::istream& operator>>(std::istream& is, Student& s) {
19     is >> s.id >> s.name >> s.major;
20     if (!is) {
21         throw std::runtime_error("字段缺失(学号/姓名/专业)");
22     }
23 
24     if (!(is >> s.grade)) {
25         throw std::runtime_error("学生 " + std::to_string(s.id) + " 成绩缺失");
26     }
27     if (s.grade < 0 || s.grade > 100) {
28         throw std::runtime_error("学生 " + std::to_string(s.id) + " 成绩无效(" + std::to_string(s.grade) + ",需0-100)");
29     }
30 
31     return is;
32 }
View Code
 1 #include "stumgr.hpp"
 2 #include <fstream>
 3 #include <algorithm>
 4 #include <stdexcept>
 5 #include <iostream>
 6 
 7 void StuMgr::load(const std::string& file) {
 8     std::ifstream ifs(file);
 9     if (!ifs.is_open()) {
10         throw std::runtime_error("无法打开文件:" + file);
11     }
12 
13     students.clear();
14 
15     std::string header;
16     std::getline(ifs, header);
17 
18     Student s;
19     while (ifs >> s) {
20         students.push_back(s);
21     }
22 
23     if (!ifs.eof() && ifs.fail()) {
24         throw std::runtime_error("文件读取失败:" + file);
25     }
26 
27     ifs.close();
28 }
29 
30 void StuMgr::sort() {
31     std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
32         if (a.get_major() != b.get_major()) {
33             return a.get_major() < b.get_major();
34         }
35         return a.get_grade() > b.get_grade();
36         });
37 }
38 
39 void StuMgr::print() const {
40     write(std::cout);
41 }
42 
43 void StuMgr::save(const std::string& file) const {
44     std::ofstream ofs(file);
45     if (!ofs.is_open()) {
46         throw std::runtime_error("无法创建/写入文件:" + file);
47     }
48 
49     write(ofs);
50     ofs.close();
51 }
52 
53 void StuMgr::write(std::ostream& os) const {
54     os << "学号    姓名    专业    成绩\n";
55     for (const auto& stu : students) {
56         os << stu << '\n';
57     }
58 }
stumgr.cpp
 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 }
task2.cpp

运行结果

image    image   image

ans.txt文本文件:

image

 

 实验总结

  本次实验中,我掌握了 C++ 标准 I/O 流的控制台与文件读写及对应异常处理,会用操控符控制数据格式;通过 try/catch 及标准异常类实现了异常处理并理清其流程;同时综合封装、继承、多态等特性与现代 C++ 标准库完成了小型应用,代码兼顾安全、高效等特性,顺利达成实验要求。

 

 

 

posted @ 2025-12-22 16:30  景思翰  阅读(5)  评论(0)    收藏  举报