实验6

实验任务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;
}
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;
}
task1.cpp
#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();
}

image

 问题1

(1)

因为  std::ofstream  是  std::ostream  的派生类,根据 C++ 的多态机制,基类引用可以绑定到派生类对象,因此同一函数无需重写即可同时处理控制台输出和文件输出。

(2)

不需要。只要新设备继承自  std::ostream ,就可以直接传入  write() ,实现“一次编写,多处复用”。

问题2

save() 中:
  std::ofstream os(filename);  打开失败时抛出
  throw std::runtime_error("fail to open " + filename); 

load() 中:
  std::ifstream is(filename);  打开失败时抛出
  throw std::runtime_error("fail to open " + filename); 

(1)

输出文件失败时

(2)

 app()  函数里的  try-catch  块捕获这两处异常

捕获后仅把错误信息打印到  stderr ,随后  main()  正常返回

问题3

可以替换,功能,性能,结果均完全一致

问题4

(1)

运行崩溃,控制台不输出任何信息

程序在  load()  里读取到空白行或字段缺失时  operator>>  进入失败状态,导致后续数据全部失效,最终返回空容器;排序、写文件阶段均对空容器操作,生成的  ans.txt  为空文件。

(2)

int lineNo = 1;
while (std::getline(is, line)) {
    ++lineNo;
    std::istringstream iss(line);
    if (!(iss >> c.id >> c.name >> c.major >> c.solved >> c.penalty)) {
        std::cerr << "line " << lineNo << " format error, skipped: " << line << "\n";
        continue;
    }
    v.push_back(c);
}

实验任务2

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

student.cpp

#include "student.hpp"

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(10) << s.name
       << std::setw(10) << 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;
}
stumgr.cpp
#include "stumgr.hpp"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <sstream>

void StuMgr::load(const std::string& file) {
    std::ifstream ifs(file);
    if (!ifs) throw std::runtime_error("cannot open file: " + file);

    std::string line;
    std::getline(ifs, line); // 跳过标题

    Student s;
    while (ifs >> s) {
        students.push_back(s);
    }
}

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 ofs(file);
    if (!ofs) throw std::runtime_error("cannot open file: " + file);
    write(ofs);
}

void StuMgr::write(std::ostream& os) const {
    for (const auto& s : students)
        os << s << "\n";
}

image

 

image

 

image

 

image

 

posted @ 2025-12-24 00:24  15468483  阅读(2)  评论(0)    收藏  举报