实验六

任务一:

1.源代码:

(1)contestant.hpp:

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

(2)utils.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;
}

(3)task1.cpp:

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

2.实验测试代码运行结果:

(1)data.txt:

image

 (2)data_bad.txt:

image

 3.回答问题:

问题一:

  (1)因为std::cout 和 std::ofstream是继承于std::cout的派生类对象;

  (2)在不考虑对象参数(Comtestant)时不需要。

问题二:

throw:

image        (1)不能打开文件时抛出异常;

(2)被try-catch块捕获,做了打印错误原因的操作;

问题三:

  可以,功能和结果一致,性能基本一致;

问题四:

(1)由于空数据等原因会出现错误数据,截图如下:

image

 (2)以下是AI生成的修改代码:(头文件加上sstream)
// 从文件读取信息(跳过标题行)
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);          // 跳过标题行(第1行)

    std::vector<Contestant> v;
    int lineNumber = 2;               // 当前读取的行号,从第2行开始(数据行)

    // 逐行读取文件
    while (std::getline(is, line)) {
        std::istringstream iss(line);
        int seq;
        Contestant t;
        
        // 尝试解析当前行
        if (iss >> seq >> t) {
            v.push_back(t);
        } else {
            // 解析失败,输出错误信息
            std::cerr << "错误:第 " << lineNumber << " 行数据格式错误,已跳过。"  << std::endl;
        }
        
        lineNumber++;  // 行号递增
    }
    
    return v;
}

可以使用sstream中的istringstream能检查该行是否解析成功,成功则返回行序号。

任务二:

1.源代码:

(1)student.hpp:

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

(2)student.cpp:

#include "student.hpp"
#include <iomanip>
#include <string>
#include <iostream>
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;
    os << std::setw(10) << s.id
        << std::setw(10) << s.name
        << std::setw(10) << s.major
        << std::setw(10) << s.grade;
    return os;
    
}
std::istream& operator>>(std::istream& is, Student& s){
    is >> s.id >> s.name >> s.major >> s.grade;
    return is;
}

(3)stumgr.hpp:

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

(4)stumgr.cpp:

#include "stumgr.hpp"
#include <string>
#include <fstream>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <iomanip> 
#include <algorithm>


void StuMgr::load(const std::string& file){
    
    std::ifstream is(file);
    if(!is){
        throw std::runtime_error("cannot open file: " + file);
        return; 
    } 
    std::string line;
    std::getline(is,line);
    int LineN = 1;
    while(std::getline(is,line)){
        std::istringstream iss(line);
        Student s;
        if(iss >> s){
            if(s.get_grade() < 0 || s.get_grade() > 100){
                std::cerr << "[Warning] line " << LineN << "format error, skipped: " << s <<std::endl; 
            }else{
                students.push_back(s);    
            } 
        }else{
            std::cerr << "[Warning] line " << LineN << "grade invalid, skipped: " << s << std::endl; 
        }
        LineN ++;
    }
} // 加载数据文件(空格分隔)

void StuMgr::sort(){
    if(students.empty()){
        std::cerr << "(emtpy)" << std::endl;
        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 os(file);
    if(!os)
        throw std::runtime_error("fail to open " + file);
    write(os);
}// 保存到文件

void StuMgr::write(std::ostream &os) const{
    for(const Student& s:students){
        os << s << '\n';
    }
} // 把数据写到任意输出流

(5)task2.cpp:

#include <iostream>
#include <limits>
#include <string>
#include "stumgr.hpp"

const std::string in_file = "./data_bad.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();
}

2.测试代码运行结果:

image

 

image

image

实验总结:
  文件流读写,使用流的方式可以实现文件和显示器交互移动,但是这样需要处理一些异常问题,这就需要用到异常处理了,也就是throw try-catch 来在不影响程序后续进行的情况下,捕获异常。

posted @ 2025-12-19 21:37  Likgon  阅读(0)  评论(0)    收藏  举报