实验六 文件I/O与异常处理
TASK1
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();
}

Q1
(1)std::cout 是 std::ostream 类型的全局对象(直接属于基类 ostream 的实例);std::ofstream 是 std::ostream 的派生类。在 C++ 中,基类的引用(或指针)可以绑定到其派生类的对象,这是多态的基础。
(2)不需要改动 write() 函数。
只要目标设备提供了标准的 std::ostream 接口(是std::ostream的派生类或兼容std::ostream&绑定),当前的 write()可以直接复用,无需任何修改。这体现了oop编程的可复用性。
Q2
(1)throw std::runtime_error("fail to open " + filename);:当无法打开要保存的文件时会抛出异常。
throw std::runtime_error("fail to open " + filename);:当无法打开要读取的文件时抛出异常。
(2)所有异常最终被 app() 函数中的 catch (const std::exception& e) 块捕获;
1.错误信息输出:
通过 e.what() 获取抛出异常时的字符串;
输出到标准错误流 std::cerr。
2.终止 app () 函数:
return 语句让 app() 立即退出,不再执行后续代码,回到 main() 函数,main() 执行完 app() 后无其他逻辑,程序以默认返回码 0 退出。
Q3
可以;功能上一致,性能上代码更内聚,减少冗余,灵活度高,略优于调用函数,结果一致。
Q4
(1)
会有脏数据,空白的数据没有默认值。
(2)逐行读取并记录行号;对每行数据做合法性校验,解析失败时打印错误行号+内容,跳过该行;用try-catch捕获单行解析异常,不终止整体读取流程。
TASK2
student.hpp
#pragma once
#include <iostream>
#include <string>
#include <stdexcept>
#include <sstream>
class Student {
public:
Student() = default;
~Student() = default;
const std::string get_major() const { return major; }
int get_grade() const { return grade; }
int get_id() const { return id; }
const std::string& get_name() const { return name; }
// 数据验证方法
void validate() const {
if (id <= 0) {
throw std::invalid_argument("学号必须为正整数");
}
if (name.empty()) {
throw std::invalid_argument("姓名不能为空");
}
if (major.empty()) {
throw std::invalid_argument("专业不能为空");
}
if (grade < 0 || grade > 100) {
std::ostringstream oss;
oss << "成绩必须在0-100之间,当前值: " << grade;
throw std::invalid_argument(oss.str());
}
}
friend std::ostream& operator<<(std::ostream& os, const Student& s) {
os << s.id << "\t" << s.name << "\t" << s.major << "\t" << s.grade;
return os;
}
friend 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("读取专业失败:字段缺失");
}
if (!(is >> s.grade)) {
throw std::runtime_error("读取成绩失败:字段缺失或格式错误");
}
try {
s.validate();
} catch (const std::exception& e) {
is.setstate(std::ios::failbit);
throw;
}
return is;
}
private:
int id;
std::string name;
std::string major;
int grade; // 0-100
};
stumgr.hpp
#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <limits>
#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 ifs(file);
if (!ifs.is_open()) {
throw std::runtime_error("无法打开文件: " + file);
}
students.clear();
std::string line;
if (!std::getline(ifs, line)) {
throw std::runtime_error("文件为空或格式错误");
}
int lineNumber = 1;
int skippedCount = 0;
while (std::getline(ifs, line)) {
lineNumber++;
if (line.empty() || line.find_first_not_of(" \t\r\n") == std::string::npos) {
continue;
}
std::istringstream iss(line);
Student s;
try {
iss >> s;
if (iss.fail()) {
throw std::runtime_error("数据格式错误");
}
students.push_back(s);
} catch (const std::exception& e) {
skippedCount++;
std::istringstream temp(line);
int id = 0;
std::string name, major;
int grade = 0;
temp >> id >> name >> major >> grade;
std::cout << "[Warning] line " << lineNumber << " ";
if (name.empty()) {
std::cout << "format error";
} else if (grade < 0 || grade > 100) {
std::cout << "grade invalid";
} else {
std::cout << "format error";
}
std::cout << ", skipped: " << id << "\t" << name << "\t" << major << "\t";
if (grade < 0 || grade > 100) {
std::cout << "error: " << grade;
}
std::cout << "\n";
}
}
if (students.empty()) {
throw std::runtime_error("文件中没有有效的学生数据");
}
std::cout << "加载成功\n";
if (skippedCount > 0) {
std::cout << "跳过了 " << skippedCount << " 条无效记录\n";
}
}
void StuMgr::sort() {
if (students.empty()) {
throw std::runtime_error("没有数据可排序,请先加载文件");
}
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 {
if (students.empty()) {
throw std::runtime_error("没有数据可打印,请先加载文件");
}
std::cout << "\n学号\t姓名\t专业\t成绩\n";
std::cout << "========================================\n";
for (const auto& s : students) {
std::cout << s << '\n';
}
std::cout << "========================================\n";
std::cout << "共 " << students.size() << " 条记录\n";
}
void StuMgr::save(const std::string& file) const {
if (students.empty()) {
throw std::runtime_error("没有数据可保存,请先加载文件");
}
std::ofstream ofs(file);
if (!ofs.is_open()) {
throw std::runtime_error("无法创建文件: " + file);
}
try {
write(ofs);
ofs.close();
if (ofs.fail()) {
throw std::runtime_error("写入文件时发生错误");
}
} catch (const std::exception& e) {
throw std::runtime_error("保存文件失败: " + std::string(e.what()));
}
}
void StuMgr::write(std::ostream &os) const {
for (const auto& s : students) {
os << s << '\n';
}
}
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();
}








浙公网安备 33010602011771号