实验6

任务一:

contestant.hpp

 1 #pragma once
 2 #include <iomanip>
 3 #include <iostream>
 4 #include <string>
 5 
 6 struct Contestant {
 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 }

utils.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) 
32         throw std::runtime_error("fail to open " + filename);
33 
34     write(os, v);
35 }
36 
37 // 从文件读取信息(跳过标题行)
38 inline std::vector<Contestant> load(const std::string& filename) {
39     std::ifstream is(filename);
40     if (!is) 
41         throw std::runtime_error("fail to open " + filename);
42 
43     std::string line;
44     std::getline(is, line);          // 跳过标题
45 
46     std::vector<Contestant> v;
47     Contestant t;
48     int seq;
49     while (is >> seq >> t) 
50         v.push_back(t);
51         
52     return v;
53 }

task1.cpp

 1 #include <algorithm>
 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     std::vector<Contestant> contestants;
13 
14     try {
15         contestants = load(in_file);                                      
16         std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 
17         print(contestants);      
18         save(out_file, contestants);                         
19     } catch (const std::exception& e) {
20         std::cerr << e.what() << '\n';
21         return;
22     }
23 }
24 
25 int main() {
26     app();
27 }

输出结果:

QQ_1766473324457

 

#问题1:流操作与代码复用

观察 print() 与 save() 的实现,均在内部调用 write() :

(1) write() 的参数类型是  std::ostream& ,它为什么能同时接受 std::cout 和 std::ofstream 对象作为实参?

std::ostream是所有输出流类的基类,std::cout和std::ofstream是std::ostream的派生类对象,可以基类的引用调用

(2)如果要把结果写到其他设备,只要该设备也提供  std::ostream 接口,还需改动 write() 吗?

不需要

##问题2:异常处理与捕获

在代码中找到两处 throw 语句,说明:

(1)什么情况下会抛出异常;

if(!os)

  throw std::runtime_error("fail to open " + filename);

if(!is)

  throw std::runtime_error("fail to open " + filename);

文件无法正常打开时

 

(2)异常被谁捕获、做了哪些处理。

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;

}

在app()函数中被捕获;

输出错误信息,提前中止函数

###问题3:替代写法

函数app中 std::sort(contestants.begin(), contestants.end(), cmp_by_solve); 参数 cmp_by_solve 换成下面的lambda表达式是否可以?功能、性能、结果是否一致?

1 [](const Contestant& a, const Contestant& b) {
2     return a.solved != b.solved ? a.solved > b.solved
3         : a.penalty < b.penalty;}  

可以;一致

####问题4:数据完整性与代码健壮性

把 in _file 改成 "./data_bad.txt" (内含空白行或字段缺失),重新编译运行:

(1)观察运行结果有什么问题?给出测试截图并分析原因。

QQ_1766474465328

 序号2-3之间的空行会导致is >> seq读取失败,会跳过前导空白

 序号7数据缺失

(2)思考:如何修改函数 std::vector load(const std::string& filename) ,使其提示出 错行号并跳过有问题的数据行,同时让程序继续执行?(选答*) 

 1 inline std::vector<Contestant> load(const std::string& filename) {
 2     std::ifstream is(filename);
 3     if (!is) 
 4         throw std::runtime_error("fail to open " + filename);
 5 
 6     std::string line;
 7     std::getline(is, line);          // 跳过标题
 8     int i = 1;
 9 
10     std::vector<Contestant> v;
11     Contestant t;
12     int seq;
13     while (std::getline(is,line)) {
14         i++;
15         if(line.empty()) {
16             std::cerr << "警告:跳过第 " << i << " 行:空行\n";
17             continue;
18         }
19         std::istringstream is_(line);
20         if(!(is_ >> seq >> t.id >> t.name >> t.major >> t.solved >> t.penalty)) {
21             std::cerr << "警告:跳过第 " << i << " 行:数据缺失:" << line << "\n";
22             continue;
23         }
24         v.push_back(t);
25     } 
26         
27     return v;
28 }

QQ_1766490644076

 

任务二:

 student.hpp

 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.cpp

#include"student.hpp"
#include<iostream>
#include<string>
#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;
    os << std::setw(8) << s.id
        << std::setw(8) << s.name
        << std::setw(8) << s.major
        << std::setw(8) << 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

 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.cpp

 1 #include"stumgr.hpp"
 2 #include<string>
 3 #include<vector>
 4 #include<iostream>
 5 #include<fstream>
 6 #include<sstream>
 7 #include<stdexcept>
 8 #include<algorithm>
 9 
10 void StuMgr::write(std::ostream &os) const {
11     for(const auto& x:students)
12         os << x << "\n";
13 }
14 
15 void StuMgr::print() const {
16     write(std::cout);
17 }
18 
19 void StuMgr::sort() {
20     std::sort(students.begin(),students.end(),
21     [](const Student &a,const Student &b){
22         return a.get_major() != b.get_major()?a.get_major()<b.get_major():a.get_grade()>b.get_grade();
23     });
24 }
25 
26 void StuMgr::save(const std::string& file) const {
27     std::ofstream os(file);
28     if(!os)
29         throw std::runtime_error("fail to open " + file);
30     write(os);
31 }
32 
33 void StuMgr::load(const std::string& file) {
34     std::ifstream is(file);
35     if(!is)
36         throw std::runtime_error("fail to open " + file);
37         
38     std::string line;
39     std::getline(is,line);
40     int i = 1;
41     Student stu;
42     while(std::getline(is,line)) {
43         i++;
44         std::istringstream is_(line);
45         if(!(is_ >> stu)) {
46             std::cerr << "[Warning] line " << i << " format error,skipped:" << line << "\n";
47             continue;
48         }
49         if(stu.get_grade() < 0 || stu.get_grade() > 100) {
50             std::cerr << "[Warning] line " << i << " grade invalid,skipped:" << line << "\n";
51             continue;
52         }
53         students.push_back(stu);
54     }
55 }

task2.cpp

 1 #include <iostream>
 2 #include <limits>
 3 #include <string>
 4 #include "stumgr.hpp"
 5 
 6 const std::string in_file = "./data.txt";
 7 const std::string out_file = "./ans.txt";
 8 
 9 void menu() {
10     std::cout << "\n**********简易应用**********\n"
11                  "1. 加载文件\n"
12                  "2. 排序\n"
13                  "3. 打印到屏幕\n"
14                  "4. 保存到文件\n"
15                  "5. 退出\n"
16                  "请选择:";
17 }
18 
19 void app() {
20     StuMgr mgr;
21 
22     while(true) {
23         menu();
24         int choice;
25         std::cin >> choice;
26 
27         try {
28             switch (choice) {
29             case 1: mgr.load(in_file); 
30                     std::cout << "加载成功\n"; break;
31             case 2: mgr.sort(); 
32                     std::cout << "排序已完成\n"; break;
33             case 3: mgr.print(); 
34                     std::cout << "打印已完成\n"; break;
35             case 4: mgr.save(out_file); 
36                     std::cout << "导出成功\n"; break;
37             case 5: return;
38             default: std::cout << "不合法输入\n";
39             }
40         }
41         catch (const std::exception& e) {
42             std::cout << "Error: " << e.what() << '\n';
43         }
44     }
45 }
46 
47 int main() {
48     app();
49 }

输出结果:

QQ_1766494984102

 

QQ_1766494989929

 

QQ_1766495047127

 

文件异常:

QQ_1766495226714

 

QQ_1766495232697

 

QQ_1766495248118

 

实验总结:

通过本次实验,我对异常处理,文件读写操作有了进一步理解,同时认识到std::ostream是所有输出流类的基类,std::cout、std::ofstream是std::ostream的派生类对象,对文件异常处理有了初步认识

 

posted @ 2025-12-23 21:16  艾拉i  阅读(0)  评论(0)    收藏  举报