实验6
1.实验任务1
此部分书写内容:
给出contestant.hpp, utils.hpp, task1.cpp源代码及运行结果截图(屏幕输出截图,及,生成数据文件ans.txt截图)
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;
}
点击查看代码
#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;
}
点击查看代码
#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();
}

回答问题
问题1:流操作与代码复用
观察 print() 与 save() 的实现,均在内部调用 write() :
(1) write() 的参数类型是 std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream对象作为实参?
回答: 因std::cout是std::ostream的实例,std::ofstream继承自std::ostream,多态特性让基类引用可接收派生类对象。
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?
回答:不需要,复用write()即可。
问题2:异常处理与捕获
在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
回答:打开文件失败时(load()和save()中if (!is)或if (!os))抛出异常。
(2)异常被谁捕获、做了哪些处理。
回答:被app()函数中的try-catch捕获,打印异常信息并返回,终止程序后续流程。
问题3:替代写法
函数 app 中 std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 参数cmp_by_solve 换成下面的lambda表达式是否可以?功能、性能、结果是否一致?
回答:可以,功能、结果完全一致;性能上lambda更好。
问题4:数据完整性与代码健壮性
把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。
回答:

data_bad.txt有字段缺失、格式错误,>>运算符读取失败时流状态置为错误,循环提前终止,且未处理错误行。
2.实验任务2
此部分书写内容:
给出student.hpp, student.cpp, stumgr.hpp, stumgr.cpp, task2.cpp源代码及运行结果截图(屏幕输出截图,及,生成数据文件ans.txt截图)
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
};
点击查看代码
#include "student.hpp"
#include <<iomanip> // 用于std::setw和std::left
// 访问器实现
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(15) << s.name
<< std::setw(15) << s.major
<< std::setw(5) << s.grade;
return os;
}
// 重载>>:按4字段顺序读取,自动跳过空格(包括跨行)
std::istream& operator>>(std::istream& is, Student& s) {
is >> s.id >> s.name >> s.major >> s.grade;
return is;
}
点击查看代码
#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;
};
点击查看代码
#include "stumgr.hpp"
#include <fstream>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <limits>
// 加载数据文件,包含健壮性处理
void StuMgr::load(const std::string& file) {
std::ifstream is(file);
if (!is) {
throw std::runtime_error("无法打开文件: " + file);
}
std::string header;
std::getline(is, header); // 跳过标题行
students.clear(); // 清空现有数据
std::string line;
int lineNum = 2; // 从第2行开始(跳过标题)
int validCount = 0, errorCount = 0;
while (std::getline(is, line)) {
// 跳过空行
if (line.empty()) {
std::cerr << "警告: 第" << lineNum << "行为空行,已跳过\n";
lineNum++;
errorCount++;
continue;
}
std::istringstream iss(line);
Student s;
try {
if (!(iss >> s)) {
throw std::runtime_error("字段缺失或格式错误");
}
// 检查是否还有多余数据(防止格式错误)
std::string extra;
if (iss >> extra) {
throw std::runtime_error("多余字段: " + extra);
}
students.push_back(s);
validCount++;
} catch (const std::exception& e) {
std::cerr << "第" << lineNum << "行错误: " << e.what()
<< " (内容: " << line << ")\n";
errorCount++;
}
lineNum++;
}
std::cout << "加载完成: 有效记录" << validCount << "条,错误" << errorCount << "条\n";
// 如果所有行都错误,抛出异常
if (validCount == 0 && errorCount > 0) {
throw std::runtime_error("文件中无有效数据");
}
}
// 排序函数
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::write(std::ostream& os) const {
// 输出标题
os << "学号 姓名 专业 成绩\n";
for (const auto& s : students) {
os << s << '\n';
}
// 输出统计信息
os << "\n总计: " << students.size() << " 条记录\n";
}
// 打印到屏幕
void StuMgr::print() const {
write(std::cout);
}
// 保存到文件
void StuMgr::save(const std::string& file) const {
if (students.empty()) {
throw std::runtime_error("无数据可保存");
}
std::ofstream os(file);
if (!os) {
throw std::runtime_error("无法保存到文件: " + file);
}
write(os);
std::cout << "数据已保存到: " << file << "\n";
}
点击查看代码
#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号