实验六

1.试验任务一

 1 #pragma once
 2 #include <iomanip>
 3 #include <iostream>
 4 #include <string>
 5 
 6 struct Contestant {//结构体访问权限默认public 
 7     long   id;              // 学号
 8     std::string name;       // 姓名
 9     std::string major;      // 专业
10     int    solved;          // 解题数
11     int    penalty;         // 总罚时
12 };
13 
14 // 重载<<
15 // 要求:姓名/专业里不含空白符
16 inline std::ostream& operator<<(std::ostream& out, const Contestant& c) {
17     out << std::left;///左对齐   默认右对齐 
18     out << std::setw(15) << c.id//设置输出宽度 
19         << std::setw(15) << c.name
20         << std::setw(15) << c.major
21         << std::setw(10) << c.solved
22         << std::setw(10) << c.penalty;
23 
24     return out;
25 }
26 
27 // 重载>>
28 inline std::istream& operator>>(std::istream& in, Contestant& c) {
29     in >> c.id >> c.name >> c.major >> c.solved >> c.penalty;
30 
31     return in;
32 }
contestant.hpp
 1 #pragma once
 2 #include <fstream>
 3 #include <iostream>
 4 #include <stdexcept>
 5 #include <string>
 6 #include <vector>
 7 #include "contestant.hpp"
 8 
 9 // ACM 排序规则:先按解题数降序,再按罚时升序
10 inline bool cmp_by_solve(const Contestant& a, const Contestant& b) {
11     if(a.solved != b.solved)
12         return a.solved > b.solved;
13     
14     return a.penalty < b.penalty;
15 }
16 
17 // 将结果写至任意输出流
18 inline void write(std::ostream& os, const std::vector<Contestant>& v) {
19     for (const auto& x : v) 
20        os << x << '\n';
21 }
22 
23 // 将结果打印到屏幕
24 inline void print(const std::vector<Contestant>& v) {
25    write(std::cout, v);
26 }
27 
28 // 将结果保存到文件
29 inline void save(const std::string& filename, const std::vector<Contestant>& v) {
30     std::ofstream os(filename);//输出文件流对象 
31     if (!os) ///os.fail() 
32         throw std::runtime_error("fail to open " + filename);
33     write(os, v);
34 }
35 
36 // 从文件读取信息(跳过标题行)
37 inline std::vector<Contestant> load(const std::string& filename) {
38     std::ifstream is(filename);
39     if (!is) 
40         throw std::runtime_error("fail to open " + filename);
41 
42     std::string line;
43     std::getline(is, line);          // 跳过标题
44 
45     std::vector<Contestant> v;
46     Contestant t;
47     int seq;
48     while (is >> seq >> t) 
49         v.push_back(t);
50         
51     return v;
52 }
utils.hpp
 1 #include <algorithm> //sort
 2 #include <iostream>
 3 #include <stdexcept> //跑错误 
 4 #include <vector>
 5 #include "contestant.hpp"
 6 #include "utils.hpp"
 7 
 8 const std::string in_file = "./data.txt";
 9 const std::string out_file = "./ans.txt";
10 
11 void app() 
12 {
13     std::vector<Contestant> contestants;
14 
15     try {
16         contestants = load(in_file); //加载读取文件                                     
17         std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 
18         print(contestants);      
19         save(out_file, contestants);                         
20     } catch (const std::exception& e) {
21         std::cerr << e.what() << '\n';  //输出抛回的信息 
22         return;
23     }
24 }
25 
26 int main() {
27     app();
28 }
task1.cpp

 屏幕输出截图:

image

 生成数据文件ans.txt截图

image

问题1:流操作与代码复用
观察 print() 与 save() 的实现,均在内部调用 write() :
(1) write() 的参数类型是 std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream
对象作为实参?
  因为std::cout和std::ofstream都是std::ostream的派生类对象
(2)如果要把结果写到其他设备,只要该设备也提供 std::ostream 接口,还需改动 write() 吗?
   不需要
问题2:异常处理与捕获
在代码中找到两处 throw 语句,说明:
(1)什么情况下会抛出异常;
  load()函数打开、读取文件内容失败
(2)异常被谁捕获、做了哪些处理。
  被上层函数中的try catch捕获;输出抛回的异常信息并终止程序
问题3:替代写法
函数 app 中 std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 参数
cmp_by_solve 换成下面的lambda表达式是否可以?功能、性能、结果是否一致?

image

 可以,是一致的

问题4:数据完整性与代码健壮性
把 in_file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:
(1)观察运行结果有什么问题?给出测试截图并分析原因。

image

   第一行thomas最后数值出现问题,原因:文件中的他的解题数和总罚时没有数据,但是代码中没有对于这个异常的捕获与处理

2.试验任务二
 
 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <string>
 5 
 6 class Student {
 7 public:
 8     Student() = default;
 9     ~Student() = default;
10     
11     const std::string get_major() const;
12     int get_grade() const;
13 
14     friend std::ostream& operator<<(std::ostream& os, const Student& s);
15     friend std::istream& operator>>(std::istream& is, Student& s);
16 
17 private:
18     int id;   
19     std::string  name;
20     std::string  major;
21     int          grade;  // 0-100
22 };
student.hpp
 1 #include<iostream>
 2 #include<iomanip>
 3 #include<string>
 4 #include<stdexcept>
 5 #include"student.hpp"
 6 
 7 using namespace std;
 8      
 9 const std::string Student::get_major() const{
10     return this->major ;
11 }
12 
13 int Student::get_grade() const{
14     return this->grade ;
15 }
16 std::istream& operator>>(std::istream& is, Student& s) {
17     is.clear();
18     is>>s.id>>s.name>>s.major>>s.grade; 
19   /*  if (!(is >> s.grade) || s.grade < 0 || s.grade > 100) {
20         throw std::out_of_range("成绩非法");
21     }*/
22     return is;
23 }
24 
25 std::ostream& operator<<(std::ostream& os, const Student& s){
26     os<<left;
27     os<<setw(15)<<s.id
28         <<setw(15)<<s.name
29         <<setw(8)<<s.major
30         <<setw(8)<<s.grade;
31     return os;
32 }
student.cpp
 1 #pragma once
 2 #include <string>
 3 #include <vector>
 4 #include "student.hpp"
 5 
 6 class StuMgr {
 7 public:
 8     void load(const std::string& file);  // 加载数据文件(空格分隔)
 9     void sort();                         // 排序: 按专业字典序升序、同专业分数降序
10     void print() const;                  // 打印到屏幕
11     void save(const std::string& file) const; // 保存到文件
12 
13 private:
14     void write(std::ostream &os) const;  // 把数据写到任意输出流
15 
16 private:
17     std::vector<Student> students;
18 };
stumgr.hpp
 1 #include "stumgr.hpp"
 2 #include <fstream>
 3 #include <stdexcept>
 4 #include <algorithm>
 5 
 6 // 加载文件(跳过表头+处理文件异常)
 7 void StuMgr::load(const std::string& file) {
 8     std::ifstream ifs(file);
 9     if (!ifs.is_open()) {
10         throw std::runtime_error("cannot open file: " + file);
11     }
12 
13     students.clear(); // 清空原有数据
14     std::string head;
15     std::getline(ifs, head); // 跳过表头(学号    姓名    专业    成绩)
16 
17     Student temp;
18     while (ifs) {
19         try {
20             ifs >> temp; 
21             students.push_back(temp);
22         } catch (const std::exception& e) {
23             std::cerr << "警告:跳过非法数据行 - " << e.what() << "\n";
24             continue;
25         }
26     }
27 }
28 inline bool cmp_by_solve(const Student& a,const Student& b){
29     if(a.get_major() != b.get_major() )return a.get_major() < b.get_major() ;
30     return a.get_grade()>b.get_grade() ;
31 }
32 
33 void StuMgr::sort() {
34     std::sort(students.begin(), students.end(), cmp_by_solve);
35 }
36 
37 void StuMgr::print() const {
38     write(std::cout);
39 }
40 
41 void StuMgr::save(const std::string& file) const {
42     std::ofstream ofs(file);
43     if (!ofs.is_open()) {
44         throw std::runtime_error("cannot create file: " + file);
45     }
46 
47     write(ofs);
48     ofs.close();
49 }
50 
51 void StuMgr::write(std::ostream& os) const {
52     for (const auto& stu : students) {
53         os << stu << "\n"; 
54     }
55 }
stumgr.cpp

屏幕输出截图:

image

image

image

 

 

posted @ 2025-12-19 09:55  zxy22213  阅读(1)  评论(0)    收藏  举报