实验六
实验任务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;
}
点击查看代码
#pragma once
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include "contestant.hpp"
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::ofstream均继承自std::ostream,多态特性允许基类引用接收派生类类对象。
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?
不需要改动,新增std::ostream子类设备可直接复用write()。
问题2:异常处理与捕获
在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
两处throw均在文件打开失败时触发即load()打开输入文件或save()打开输出文件失败。
(2)异常被谁捕获、做了哪些处理。
异常被app()函数中的try-catch捕获,打印错误信息并终止程序执行。
问题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;}
可以。Lambda 表达式与cmp_by_solve函数逻辑完全一致,功能、结果相同,性能无差异。
问题4:数据完整性与代码健壮性
把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。

运行异常:程序读取不完整数据。
原因:data_bad.txt含空白行、字段缺失、非数值数据等数值污染,>>运算符读取失败时流状态置为错误,循环终止。
实验任务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
};
点击查看代码
#include "student.hpp"
#include <iomanip>
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(6) << s.grade;
return os;
}
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 <stdexcept>
#include <algorithm>
#include <iomanip>
#include <string>
void StuMgr::load(const std::string& file) {
std::ifstream is(file);
if (!is) {
throw std::runtime_error("cannot open file: " + file);
}
students.clear();
std::string title;
std::getline(is, title);
Student tmp;
while (is >> tmp) {
students.push_back(tmp);
}
is.close();
}
void StuMgr::sort() {
if (students.empty()) {
std::cout << "(empty)\n";
}
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.is_open()) {
throw std::runtime_error("cannot open file: " + file);
}
write(os);
os.close();
}
void StuMgr::write(std::ostream& os) const {
for (const auto& stu : students) {
os << stu << std::endl;
}
}
点击查看代码
#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号