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

实验任务1:

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;
}
contestant.hpp
#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

2.运行测试截图

image

 ans.txt

image

3.问题回答

问题一:

答:

(1)std::coutstd::ostream的实例,std::ofstream继承自std::ostream,C++ 中基类引用可以绑定到派生类对象

(2)不用,只要输出设备对应的流类继承自std::ostream,write()的std::ostream&参数可直接适配

问题二:

答:

出现在utils.hpp的save()和load()函数中

(1)save()中:std::ofstream os(filename)打开文件失败时抛出。

       load()中:std::ifstream is(filename)打开文件失败时抛出。

(2)通过try-catch块捕获std::exception,打印异常信息,避免程序崩溃。

问题三:

答:可以,功能、性能、结果完全一致,Lambda 表达式作为匿名函数,无需单独定义函数

问题四:

答:

(1)

image

程序会抛出异常,operator>>重载按id/name/major/solved/penalty的顺序读取,如果缺失字段,会触发流状态错误,load()中循环读取失败,最终数据读取不完整。

 

实验任务2:

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
};
student.hpp
#include "student.hpp"
#include <stdexcept>
#include <iostream>
#include <sstream>

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 << s.id << "\t" << s.name << "\t" << s.major << "\t" << s.grade;
    return os;
}

std::istream& operator>>(std::istream& is, Student& s) {
    if (!(is >> s.id)) {
        throw std::runtime_error("学号无效:应为整数类型");
    }

    if (!(is >> s.name)) {
        throw std::runtime_error("姓名字段缺失或格式异常");
    }

    if (!(is >> s.major)) {
        throw std::runtime_error("专业字段缺失或格式异常");
    }

    std::string grade_str;
    if (!(is >> grade_str)) {
        throw std::runtime_error("成绩无效:字段缺失(未提供成绩信息)");
    }

    try {
        size_t pos;
        s.grade = std::stoi(grade_str, &pos);
        if (pos != grade_str.length()) {
            throw std::invalid_argument("包含非数字字符");
        }
    } catch (const std::invalid_argument&) {
        throw std::runtime_error("成绩无效:应为整数类型");
    } catch (const std::out_of_range&) {
        throw std::runtime_error("成绩无效:数字超出整数存储范围");
    }

    if (s.grade < 0) {
        throw std::invalid_argument("成绩无效:小于最小值0(合法范围0-100)");
    } else if (s.grade > 100) {
        throw std::invalid_argument("成绩无效:大于最大值100(合法范围0-100)");
    }

    return is;
}
student.cpp
#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;
};
stumgr.hpp
#include "stumgr.hpp"
#include <fstream>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <limits>

void StuMgr::load(const std::string& file) {
    std::ifstream ifs(file);

    if (!ifs.is_open()) {
        throw std::runtime_error("cannot open file: " + file);
    }

    students.clear(); 
    Student temp_stu;
    int line_num = 0;

    while (ifs) {
        line_num++;
        try {
            ifs >> temp_stu;
            if (ifs.eof()) break;
            students.push_back(temp_stu);
        } catch (const std::exception& e) {
            std::cerr << "Error: line " << line_num << ": " << e.what() <<"\n";
            ifs.clear(); 
            ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 忽略当前行剩余内容
        }
    }

    ifs.close();
}

void StuMgr::sort() {
    if (students.empty()) {
        std::cout << "(empty)\n";
        return;
    }

    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::print() const {
    write(std::cout);
}

void StuMgr::save(const std::string& file) const {
    std::ofstream ofs(file);
    if (!ofs.is_open()) {
        throw std::runtime_error("cannot open file: " + file);
    }
    write(ofs);
    ofs.close();
}

void StuMgr::write(std::ostream& os) const {
    for (const auto& stu : students) {
        os << stu << "\n";
    }
}
stumgr.cpp
#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();
}
task2.cpp

2.运行测试截图

image

image

image

image

posted @ 2025-12-22 19:26  Coisini12  阅读(4)  评论(0)    收藏  举报