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

实验任务一:

源代码:

#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;
}
contestant.hpp
#pragma once
#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;
}
utils.hpp
#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();
}
task1.cpp

运行结果截图:

 

image

 

回答问题:

问题1:

流操作与代码复用 观察 print() 与 save() 的实现,均在内部调用 write() :

(1) write() 的参数类型是  std::ostream& , 它为什么能同时接受 std::cout 和 std::ostream& 对象作为实参?

  std::ostream是抽象基类,std::coutstd::ofstream均是其派生类。根据多态的特性,派生类对象可以隐式转换为基类引用,因此write()std::ostream&参数能同时接受两者作为实参。

(2)如果要把结果写到其他设备,只要该设备也提供 std::ofstream 对象作 std::ostream 接口,还需改动 write() 吗?

  无需改动。

问题2:异常处理与捕获

在代码中找到两处throw 语句,说明:

(1)什么情况下会抛出异常;

  函数save():当打开输出文件失败时,std::ofstream os(filename)创建失败,!os为真,抛出std::runtime_error(错误信息含文件名)。

  函数load():当打开输入文件失败时,std::ifstream is(filename)创建失败,!is为真,抛出std::runtime_error(错误信息含文件名)。

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

  异常被app()函数中的try-catch块捕获。

  处理:输出异常信息到标准错误流std::cerr,函数返回,程序被迫终止。

问题3:替代写法

函数app中std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 参数cmp_by_solve 换成下面的lambda表达式是否可以?功能、性能、结果是否一致?
  可以替换,功能、性能、结果一致。

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

   

image

 

  原因:load()函数无法进行数据校验和错误恢复,一旦出现字段缺失、类型不匹配等错误,无法处理。

 (2)思考:如何修改函数std::vector<Contestant> load(const std::string& filename) ,使其提示出错行号并跳过有问题的数据行,同时让程序继续执行?

  

image

 

image

 

实验任务二:

 源代码:

 1 #pragma once
 2 
 3 
 4 #include <iostream>
 5 #include <string>
 6 
 7 class Student {
 8 public:
 9     Student() = default;
10     ~Student() = default;
11 
12     const std::string get_major() const;
13     int get_grade() const;
14 
15     friend std::ostream& operator<<(std::ostream& os, const Student& s);
16     friend std::istream& operator>>(std::istream& is, Student& s);
17 
18 private:
19     int id;
20     std::string  name;
21     std::string  major;
22     int          grade;  // 0-100
23 };
student.hpp
 1 #pragma once
 2 #pragma once
 3 #include <string>
 4 #include <vector>
 5 #include "student.hpp"
 6 
 7 class StuMgr {
 8 public:
 9     void load(const std::string& file);  // 加载数据文件(空格分隔)
10     void sort();                         // 排序: 按专业字典序升序、同专业分数降序
11     void print() const;                  // 打印到屏幕
12     void save(const std::string& file) const; // 保存到文件
13 
14 private:
15     void write(std::ostream& os) const;  // 把数据写到任意输出流
16 
17 private:
18     std::vector<Student> students;
19 };
stumgr.hpp
#include<iostream>
#include<iomanip>
#include "student.hpp"
using namespace std;

ostream& operator<<(std::ostream& os, const Student& s) {
    os << std::left
        << std::setw(10) << s.id
        << std::setw(10) << s.name
        << std::setw(10) << s.major
        << std::setw(10) << s.grade;
    return os;

}

istream& operator>>(std::istream& is, Student& s) {
    is >> s.id >> s.name >> s.major >> s.grade;
    return is;

}
const std::string Student::get_major() const {
    return major;
}
int Student::get_grade() const {
    return grade;
}
student.cpp
 1 #include "stumgr.hpp"
 2 #include <fstream>
 3 #include <stdexcept>
 4 #include <algorithm>
 5 #include <iomanip>
 6 #include <sstream>
 7 using namespace std;
 8 
 9 
10 void StuMgr::load(const string& file) {    // 加载数据文件(空格分隔)
11     
12     Student s;
13     std::ifstream is(file);
14     if (!is)
15         throw std::runtime_error("fail to open" + file);
16     std::string line;
17     std::getline(is, line);
18 
19     while (is >> s) {
20         students.push_back(s);
21     }
22 }
23 
24 
25 void StuMgr::sort() {           // 排序: 按专业字典序升序、同专业分数降序
26     std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
27         if (a.get_major() != b.get_major()) {
28             return a.get_major() < b.get_major(); // 专业字典序升序
29         }
30         return a.get_grade() > b.get_grade();    // 同专业成绩降序
31         });
32 }
33 
34 
35 void StuMgr::print() const {    // 打印到屏幕
36 
37     if (students.empty()) {
38         throw std::runtime_error("没有加载学生数据,无法输出结果");
39         return;
40     }
41     write(cout);
42 }
43 
44 
45 void StuMgr::save(const string& file) const {   // 保存到文件
46     ofstream os(file);
47     if (!os) {
48         throw runtime_error("cannot open file: " + file);
49     }
50     write(os);
51     os.close();
52 }
53 
54 
55 void StuMgr::write(ostream& os) const {        // 把数据写到任意输出流
56    
57     os << left<< setw(10) << "学号"<< setw(10) << "姓名"<< setw(10) << "专业"<< setw(10) << "成绩" << '\n';
58     
59     for (const auto& s : students) {
60         os << s << '\n';
61     }
62 }
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

 

实验总结:

1.复习了 C++ 流类库的使用:iostream(控制台 I/O)、fstream(文件 I/O)、sstream(字符串流)。

2.复习异常处理机制:throw抛出异常、try-catch捕获异常,避免程序崩溃。

3.同时要注意处理文件中的异常数据。

posted @ 2025-12-17 22:07  pithia  阅读(3)  评论(0)    收藏  举报