NUIST-OOP-LAB06

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

一、实验目的

  1. 会用标准 I/O 流 ( iostream / fstream ) 完成控制台和文件的读/写,并处理读/写过程中的异常。
  2. 会用操控符及流成员函数控制数据格式。
  3. 会用 throw/try/catch 及标准库异常类处理异常,并能解释异常处理流程。
  4. 能综合应用封装、继承、多态及现代 C++ 标准库实现一个小型完整应用,确保代码正确,并注意安全、高效、
    可移植与可扩展。

二、实验准备

浏览/复习以下教材章节:

  1. 第11章 流类库与输入输出
  2. 第12章 异常处理

三、实验内容

  1. 实验任务1
    验证性实验。综合应用运算符重载、文件I/O、异常处理、标准库实现一个简单综合应用。运行、理解代码,回答问
    题。
  • 问题场景描述
    校级 ACM 集训队选拔赛后,将学员信息(学号、姓名、专业)与成绩(解题数、总罚时)存入 data.txt,格式
    如下:
    image
    要求:
    从文件加载参赛选手信息,按照ACM排序规则处理后,输出到屏幕,同时保存到文件。
  • 代码组织
    • contestant.hpp结构体 Contestant 定义及其重载运算符函数>>和<<实现
    • utils.hpp工具函数实现(排序函数、数据读/写)
    • task1.cpp应用代码 + main
#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 <sstream>
#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::ios_base::failure("fail to open " + filename);

    write(os, v);
}

// 从文件读取信息(跳过标题行)
inline std::vector<Contestant> load(const std::string& filename) {
    std::ifstream is(filename);
    if (!is) 
        throw std::ios_base::failure("fail to open " + filename);

    std::string line;
    if (!std::getline(is, line))  // 跳过标题
        throw std::ios_base::failure("file " + filename + " missing header");

    std::vector<Contestant> v;
    Contestant t;
    int seq;
    std::size_t line_no = 1;
    while (std::getline(is, line)) {
        ++line_no;

        if (line.find_first_not_of(" \t\r") == std::string::npos)
            continue;

        std::istringstream row(line);
        if (!(row >> seq >> t)) {
            std::cerr << "skip invalid line " << line_no << " in " << filename << ": " << line << '\n';
            continue;
        }

        v.push_back(t);
    }
        
    return v;
}


#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;
}

image

  1. 实验任务2
    设计性实验。用面向对象编程实现成绩处理。
  • 问题场景描述
    某艺术院系学员专业课成绩信息保存在文件data.txt中。格式如下:
    image
    要求用面向对象分析、设计,综合运用封装、I/O流、异常处理编程实现成绩处理。
#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();
}
#pragma once
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
#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;
};

void StuMgr::load(const std::string& file) {
    std::ifstream in(file);
    if (!in)
        throw std::ios_base::failure("fail to open " + file);

    std::string line;
    if (!std::getline(in, line))
        throw std::ios_base::failure(file + " is empty");

    students.clear();
    Student s;
    std::size_t line_no = 1;
    while (std::getline(in, line)) {
        ++line_no;

        if (line.find_first_not_of(" \t\r") == std::string::npos)
            continue;

        std::istringstream row(line);
        if (!(row >> s)) {
            std::cerr << "skip invalid line " << line_no << " in " << file << ": " << line << '\n';
            continue;
        }

        if (s.get_grade() < 0 || s.get_grade() > 100) {
            std::cerr << "skip invalid grade at line " << line_no << " in " << file << ": " << line << '\n';
            continue;
        }

        students.push_back(s);
    }

    if (students.empty())
        throw std::runtime_error("no valid data in " + file);
}

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

void StuMgr::save(const std::string& file) const {
    std::ofstream out(file);
    if (!out)
        throw std::ios_base::failure("fail to open " + file);

    write(out);
}

void StuMgr::write(std::ostream &os) const {
    os << "学号\t姓名\t专业\t成绩\n";
    for (const auto& s : students)
        os << s << '\n';
}
#pragma once

#include <iomanip>
#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
};

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(12) << s.name
       << std::setw(12) << s.major
       << std::setw(5)  << s.grade;
    return os;
}

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


image

image

四、实验结论

  1. 实验任务1
    image
    Q1:
  2. 都是ostream的派生类
  3. 不需要

Q2:

  1. 调用save函数的时候无法打开输出文件
  2. 异常被app()中的catch exception捕获,打印了报错内容并退出函数

Q3:

  1. 功能一致,性能相当于普通内联函数,结果一致

Q4:

  1. 第一行数据出现严重异常,如图

  2. 如代码所示
    image

  3. 实验任务2
    image
    image
    为save和load添加了错误处理,具体见上方代码

posted @ 2025-12-20 13:50  witlethe  阅读(4)  评论(0)    收藏  举报