Test6
任务一
源代码
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();
}
结果展示


实验结论
问题1:流操作与代码复用
观察print()与save()的实现,均在内部调用write():
(1)write()的参数类型是std::ostream&,它为什么能同时接受std::cout和 std::ofstream对象作为实参?
答:std::ostream&是输出流的基类接口,std::cout是一个std::ostream对象,而std::ofstream继承自std::basic_ostream<char>,用基类引用作为形参,可以实现多态复用。
(2)如果要把结果写到其他设备,只要该设备也提供std::ostream接口,还需改动write()吗?
答:不需要。因为题意明确表示了该设备也提供std::ostream接口。
问题2:异常处理与捕获
在代码中找到两处throw语句,说明:
(1)什么情况下会抛出异常;
答:在save()中:
std::ofstream os(filename);
if (!os)
throw std::runtime_error("fail to open " + filename);
在load()中:
std::ifstream is(filename);
if (!is)
throw std::runtime_error("fail to open " + filename);
(2)异常被谁捕获、做了哪些处理。
答:在app()的try { ... } catch (const std::exception& e)中被捕获。
处理是输出错误信息std::cerr << e.what() << '\n',然后return(终止该函数),避免程序崩溃。
问题3:替代写法
函数app中std::sort(contestants.begin(), contestants.end(), cmp_by_solve);
参数cmp_by_solve换成下面的lambda表达式是否可以?功能、性能、结果是否一致?
[](const Contestant& a, const Contestant& b) {
return a.solved != b.solved ? a.solved > b.solved
: a.penalty < b.penalty;}
答:可以。功能、性能、结果一致。
两种方式逻辑一致,都会被当作内联函数进行调用,功能、性能、结果应该是一致的。
问题4:数据完整性与代码健壮性
把in_file改成"./data_bad.txt"(内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。
答:
数据错位混乱:第一条记录 Thomas 的解题数显示为 8,罚时显示为 204942078。
原因:data_bad.txt 中该记录 204942076 Thomas 未来专业6 缺少解题数和罚时
流提取器在读取时失败,试图从下一行继续读取,导致第9行的数据(8 204942078 Jennie...)被误读成了 Thomas 的字段。
部分数据被跳过或损坏:刚才的缺失字段导致流的提取器进入失败状态,后续数据(9 204942079 Tibby...和10 204942080 Vermont...)被跳过了。
(2)思考:如何修改函数std::vector<Contestant> load(const std::string& filename),使
其提示出错行号并跳过有问题的数据行,同时让程序继续执行?(选答*)
答:
// 从文件读取信息(跳过标题行,并处理坏数据)
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;
int lineN = 2; // 从标题后第一行开始计数
while (std::getline(is, line))
{
// 跳过空白行
if (line.empty())
{
++lineN;
continue;
}
std::istringstream ist(line);
int seq;
Contestant t;
// 尝试解析当前行
if (!(ist >> seq >> t.id >> t.name >> t.major >> t.solved >> t.penalty))
{
std::cerr << "Warning: bad data at line " << lineN
<< ": " << line << " (skipped)\n";
++lineN;
continue;
}
v.push_back(t);
++lineN;
}
return v;
}

任务二
源代码
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
};
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 << s.id << "\t" << s.name << "\t" << s.major << "\t" << s.grade;
return os;
}
std::istream &operator>>(std::istream &is, Student &s)
{
is >> s.id >> s.name >> s.major >> s.grade;
return is;
}
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;
};
stumgr.cpp
点我展开代码
#include "stumgr.hpp"
#include <fstream>
#include <algorithm>
#include <sstream>
#include <iostream>
void StuMgr::load(const std::string &file)
{
std::ifstream ifs(file);
if (!ifs)
{
throw std::runtime_error("无法打开文件: " + file);
}
std::string line;
// 跳过标题行
if (!std::getline(ifs, line))
{
throw std::runtime_error("数据文件为空");
}
int lineNo = 2; // 数据从第2行开始
while (std::getline(ifs, line))
{
if (line.empty())
{
std::cerr << "[Warning] line " << lineNo << " empty, skipped\n";
++lineNo;
continue;
}
std::istringstream iss(line);
Student s;
if (!(iss >> s))
{
std::cerr << "[Warning] line " << lineNo << " format error, skipped: " << line << "\n";
++lineNo;
continue;
}
if (s.get_grade() < 0 || s.get_grade() > 100)
{
std::cerr << "[Warning] line " << lineNo << " grade invalid, skipped: " << line << "\n";
++lineNo;
continue;
}
students.push_back(s);
++lineNo;
}
}
void StuMgr::sort()
{
if (students.empty())
{
std::cout << "学生列表为空\n";
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
{
if (students.empty())
{
std::cout << "学生列表为空\n";
return;
}
write(std::cout);
}
void StuMgr::save(const std::string &file) const
{
std::ofstream ofs(file);
if (!ofs)
{
throw std::runtime_error("无法打开文件: " + file);
}
write(ofs);
}
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_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();
}
结果展示




实验结论
拓展(选做*)
说明为解决数据完整性、有效性,提升代码健壮性,对哪些模块做了改动。
提供改动模块的源码及使用data_bad.txt运行测试效果截图。
主要是完善了void StuMgr::load(const std::string &file)
void StuMgr::load(const std::string &file)
{
std::ifstream ifs(file);
if (!ifs)
{
throw std::runtime_error("无法打开文件: " + file);
}
std::string line;
// 跳过标题行
if (!std::getline(ifs, line))
{
throw std::runtime_error("数据文件为空");
}
int lineNo = 2; // 数据从第2行开始
while (std::getline(ifs, line))
{
if (line.empty())
{
std::cerr << "[Warning] line " << lineNo << " empty, skipped\n";
++lineNo;
continue;
}
std::istringstream iss(line);
Student s;
if (!(iss >> s))
{
std::cerr << "[Warning] line " << lineNo << " format error, skipped: " << line << "\n";
++lineNo;
continue;
}
if (s.get_grade() < 0 || s.get_grade() > 100)
{
std::cerr << "[Warning] line " << lineNo << " grade invalid, skipped: " << line << "\n";
++lineNo;
continue;
}
students.push_back(s);
++lineNo;
}
}



实验总结
流复用:write(std::ostream&)统一输出接口,既支持std::cout也支持std::ofstream,通过基类引用实现复用。
异常处理:文件打开失败在load()/save()抛runtime_error,app()中统一捕获并打印错误,程序安全退出。
排序逻辑:非捕获lambda与命名比较函数等价、性能一致。
坏数据问题:纯流式提取易因缺字段产生错位、无行号定位。改为“逐行读取 + 行内解析 + 校验 + 跳过”,输出带行号的警告,继续处理后续数据。
浙公网安备 33010602011771号