首页 > 其他分享 >实验6 模板类、文件I/O和异常处理

实验6 模板类、文件I/O和异常处理

时间:2024-12-16 21:53:16浏览次数:3  
标签:std 文件 const index get Complex 实验 include 模板

任务1

Complex.hpp

  1 #pragma once
  2 
  3 #include <iostream>
  4 #include <stdexcept>
  5 
  6 // 声明
  7 ////////////////////////////////////////////////////
  8 // 复数模板类声明
  9 template<typename T>
 10 class Complex {
 11 public:
 12     Complex(T r = 0, T i = 0);
 13     Complex(const Complex<T> &c);
 14 
 15     T get_real() const;
 16     T get_imag() const;
 17 
 18     // 重载+=为成员函数
 19     Complex<T>& operator+=(const Complex<T> &c);
 20 
 21     // 重载<<、>>为友元函数
 22     template<typename T1>
 23     friend std::ostream& operator<<(std::ostream &out, const Complex<T1> &c);
 24 
 25     template<typename T1>
 26     friend std::istream& operator>>(std::istream &in, Complex<T1> &c);
 27 
 28 private:
 29     T real, imag;
 30 };
 31 
 32 // 普通函数声明
 33 // 重载+用于Complex类型
 34 template<typename T>
 35 Complex<T> operator+(const Complex<T> &c1, const Complex<T> &c2);
 36 
 37 // 重载==用于Complex类型
 38 template<typename T>
 39 bool operator==(const Complex<T> &c1, const Complex<T> &c2);
 40 
 41 
 42 // 实现
 43 ////////////////////////////////////////////////////
 44 // 成员函数模板实现
 45 template<typename T>
 46 Complex<T>::Complex(T r, T i): real{r}, imag{i} {
 47 }
 48 
 49 template<typename T>
 50 Complex<T>::Complex(const Complex<T> &c): real{c.real}, imag{c.imag} {
 51 }
 52 
 53 template<typename T>
 54 T Complex<T>::get_real() const {
 55     return real;
 56 }
 57 
 58 template<typename T>
 59 T Complex<T>::get_imag() const {
 60     return imag;
 61 }
 62 
 63 // 重载+=为成员函数
 64 template<typename T>
 65 Complex<T>& Complex<T>::operator+=(const Complex<T> &c) {
 66     real += c.real;
 67     imag += c.imag;
 68 
 69     return *this;
 70 }
 71 
 72 ///////////////////////////////////////
 73 // 友元函数模板实现
 74 template<typename T1>
 75 std::ostream& operator<<(std::ostream &out, const Complex<T1> &c) {
 76     if(c.imag >= 0)
 77         out << c.real << " + " << c.imag << "i";
 78     else
 79         out << c.real << " - " << -c.imag << "i";
 80     
 81     return out;
 82 }
 83 
 84 template<typename T1>
 85 std::istream& operator>>(std::istream &in, Complex<T1> &c) {
 86     in >> c.real >> c.imag;
 87 
 88     return in;
 89 }
 90 
 91 ///////////////////////////////////////
 92 // 普通函数模板实现
 93 // 重载+用于Complex类型
 94 template<typename T>
 95 Complex<T> operator+(const Complex<T> &c1, const Complex<T> &c2) {
 96     return Complex<T>(c1.get_real()+c2.get_real(), 
 97                       c1.get_imag()+c2.get_imag());
 98 }
 99 
100 // 重载==用于Complex类型
101 template<typename T>
102 bool operator==(const Complex<T> &c1, const Complex<T> &c2) {
103     return c1.get_real() == c2.get_real() && 
104            c1.get_imag() && c2.get_imag();
105 }

task1.cpp

 1 #include "Complex.hpp"
 2 #include <iostream>
 3 #include <fstream>
 4 #include <stdexcept>
 5 
 6 void test1();
 7 void test2();
 8 
 9 int main() {
10     using namespace std;
11 
12     cout << "测试1: 复数模板类测试" << endl;
13     test1();
14 
15     cout << "\n测试2: 文件I/O测试" << endl;
16     test2();
17 }
18 
19 void test1() {
20     using namespace std;
21 
22     Complex<double> c1{3.5, 2}, c2;
23     cout << "Enter c2: ";
24     cin >> c2;
25     cout << "c1 = " << c1 << endl;
26     cout << "c2 = " << c2 << endl;
27     cout << "c1 == c2: " << boolalpha << (c1 == c2) << endl;
28 
29     cout << "c1 + c2 = " << c1 + c2 << endl;
30     c1 += c2;
31     cout << "c1.real = " << c1.get_real() << endl;
32     cout << "c1.imag = " << c1.get_imag() << endl;
33 
34     cout << "c1 == c2: " << boolalpha << (c1 == c2) << endl;
35 }
36 
37 void test2() {
38     using namespace std;
39 
40     Complex<int> c1{1, 2}, c2{9, -7};
41     ofstream out("ans.txt");
42     if(!out.is_open()) {
43         cout << "fail to open file ans.txt to write\n";
44         return;
45     }
46 
47     out << "c1 = " << c1 << endl;
48     out << "c2 = " << c2 << endl;
49     out << "c1 + c2 = " << c1 + c2 << endl;
50     out << "(c1 == c2) = " << boolalpha << (c1 == c2) << endl;
51 
52     out.close();
53     cout << "测试ok!" << endl;
54 }

运行结果截图:

 任务2

Contestant.hpp

 1 #pragma once
 2 
 3 #include <iostream>
 4 #include <iomanip>
 5 #include <string>
 6 
 7 using std::string;
 8 using std::ostream;
 9 using std::istream;
10 using std::setw;
11 using std::setprecision;
12 using std::setiosflags;
13 using std::ios_base;
14 
15 // Contestant类声明
16 class Contestant {
17 public:
18     Contestant() = default;
19     ~Contestant() = default;
20 
21     int get_num() const { return num; }
22     float get_time_usage() const { return time_usage; }
23 
24     friend ostream& operator<<(ostream &out, const Contestant &c);
25     friend istream& operator>>(istream &in, Contestant &c);
26 
27 private:
28     string no;          // 学号
29     string name;        // 姓名
30     string major;       // 专业
31     int num;            // 解题数
32     float time_usage;   // 总用时
33 };
34 
35 // 友元函数实现
36 // 重载流插入运算符<<
37 ostream& operator<<(ostream &out, const Contestant &c) {
38     out << setiosflags(ios_base::left);
39     out << setw(15) << c.no
40         << setw(15) << c.name
41         << setw(15) << c.major
42         << setw(5) << c.num
43         << setprecision(2) << c.time_usage;
44     
45     return out;
46 }
47 
48 // 重载流提取运算符>>
49 istream& operator>>(istream &in, Contestant &c) {
50     in >> c.no >> c.name >> c.major >> c.num >> c.time_usage;
51 
52     return in;
53 }

utils.hpp

 1 #include "Contestant.hpp"
 2 #include <fstream>
 3 #include <iostream>
 4 #include <string>
 5 #include <vector>
 6 
 7 // 排序函数
 8 // 按解题数比较,解题数相同的情况下,按总用时比较,总用时越少,排名越靠前
 9 bool compare_by_solutionInfo(const Contestant &c1, const Contestant &c2) {
10     if(c1.get_num() > c2.get_num())
11         return true;
12     
13     if(c1.get_num() == c2.get_num())
14         return c1.get_time_usage() < c2.get_time_usage();
15     
16     return false;
17 }
18 
19 // 把vector<Constestant>对象中的元素插入到输出流out
20 void output(std::ostream &out, const std::vector<Contestant> &v) {
21     for(auto &i: v)
22         out << i << std::endl;
23 }
24 
25 
26 // 把vector<Contestant>对象中的元素写到filename文件中
27 void save(const std::string &filename, std::vector<Contestant> &v) {
28     using std::ofstream;
29 
30     ofstream out(filename);
31     if(!out.is_open()) {
32         std::cout << "fail to open file to write\n";
33         return;
34     }
35 
36     output(out, v);
37     out.close();
38 }
39 
40 // 从文件filename读取参赛选手信息到vector<Contestant>对象
41 void load(const std::string &filename, std::vector<Contestant> &v) {
42     using std::ifstream;
43 
44     ifstream in(filename);
45     if(!in.is_open()) {
46         std::cout << "fail to open file to read\n";
47         return;
48     }
49 
50     std::string title_line;
51     getline(in, title_line);     // 跳过标题行
52 
53     int first_column;
54     Contestant t;
55     while(in >> first_column >> t) 
56         v.push_back(t);
57 
58     in.close();
59 }

task2.cpp

 1 #include "Contestant.hpp"
 2 #include "utils.hpp"
 3 #include <iostream>
 4 #include <vector>
 5 #include <algorithm>
 6 
 7 
 8 void test() {
 9     using namespace std;
10 
11     vector<Contestant> v;
12 
13     load("data2.txt", v);   // 从文件加载选手信息到对象v
14     sort(v.begin(), v.end(), compare_by_solutionInfo);  // 按解题情况排序
15     output(cout, v);    // 输出对象v中信息到屏幕
16     save("ans.txt", v); // 把对象v中选手信息保存到文件
17 }
18 
19 int main() {
20     test();
21 }

运行结果截图:

 

 任务3

Triangle.hpp

 1 #include <iostream>
 2 #include <stdexcept>
 3 #include <cmath>
 4 
 5 using namespace std;
 6 
 7 class Triangle {
 8 public:
 9     Triangle(double s1, double s2, double s3);
10     ~Triangle() = default;
11 
12     double area() const;
13 
14 private:
15     double a, b, c;
16 };
17 
18 Triangle::Triangle(double s1, double s2, double s3): a{s1}, b{s2}, c{s3} {
19     if(a <= 0 || b <= 0 || c <= 0)
20         throw invalid_argument("边长出现负值");
21         
22     if(a+b <= c || b+c <= a || a+c <= b) 
23         throw invalid_argument("不满足任意两边之和大于第三边");
24 }
25 
26 double Triangle::area() const {
27     double s = (a + b + c)/2;
28     return sqrt(s*(s-a)*(s-b)*(s-c));
29 }

task3.cpp

 1 #include "Triangle.hpp"
 2 #include <iostream>
 3 #include <fstream>
 4 
 5 void test() {
 6     using namespace std;
 7 
 8     cout << "从文件读入三角形三边边长,计算面积" << endl;
 9 
10     ifstream in("data3.txt");
11     if(!in.is_open()) {
12         cout << "fail to open file to read\n";
13         return;
14     }
15 
16     double a,b,c;
17     do {
18         cout << "三角形边长: ";
19         in >> a >> b >> c;
20         cout << a << " " << b << " " << c << endl;
21 
22         try {
23             Triangle t(a, b, c);
24             cout << "三角形面积: " << t.area() << endl << endl;
25         }catch(const exception &e) {
26             cout << "error: " << e.what() << endl << endl;
27         }
28 
29         if(in.peek() == EOF)
30             break;
31     } while(1);
32 
33     in.close();
34 }
35 
36 int main() {
37     test();
38 }

运行结果截图:

 任务4

Vector.hpp

 1 #ifndef VECTOR_HPP
 2 #define VECTOR_HPP
 3 
 4 #include <iostream>
 5 #include <stdexcept>
 6 
 7 template <typename T>
 8 class Vector {
 9 private:
10     T* data;      
11     int size;         
12 
13 public:
14     Vector(int n, const T& value = T()) {
15         if (n < 0) throw std::length_error("Vector constructor: negative size");
16         size = n;
17         data = new T[size];
18         for (int i = 0; i < size; ++i) {
19             data[i] = value;
20         }
21     }
22     Vector(const Vector<T>& other) {
23         size = other.size;
24         data = new T[size];
25         for (int i = 0; i < size; ++i) {
26             data[i] = other.data[i];
27         }
28     }
29     ~Vector() {
30         delete[] data;
31     }
32     int get_size() const {
33         return size;
34     }
35     T& at(int index) {
36         if (index < 0 || index >= size) throw std::out_of_range("Vector: index out of range");
37         return data[index];
38     }
39 
40     const T& at(int index) const {
41         if (index < 0 || index >= size) throw std::out_of_range("Vector: index out of range");
42         return data[index];
43     }
44     T& operator[](int index) {
45         if (index < 0 || index >= size) throw std::out_of_range("Vector: index out of range");
46         return data[index];
47     }
48 
49     const T& operator[](int index) const {
50         if (index < 0 || index >= size) throw std::out_of_range("Vector: index out of range");
51         return data[index];
52     }
53     template <typename U>
54     friend void output(const Vector<U>& v);
55 };
56 template <typename T>
57 void output(const Vector<T>& v) {
58     for (int i = 0; i < v.size; ++i) {
59         std::cout << v.data[i] << " ";
60     }
61     std::cout << std::endl;
62 }
63 
64 #endif // VECTOR_HPP

 

task4.cpp

 1 #include <iostream>
 2 #include "Vector.hpp"
 3 
 4 void test1() {
 5     using namespace std;
 6 
 7     int n;
 8     cout << "Enter n: ";
 9     cin >> n;
10     
11     Vector<double> x1(n);
12     for(auto i = 0; i < n; ++i)
13         x1.at(i) = i * 0.7;
14 
15     cout << "x1: "; output(x1);
16 
17     Vector<int> x2(n, 42);
18     const Vector<int> x3(x2);
19 
20     cout << "x2: "; output(x2);
21     cout << "x3: "; output(x3);
22 
23     x2.at(0) = 77;
24     x2.at(1) = 777;
25     cout << "x2: "; output(x2);
26     cout << "x3: "; output(x3);
27 }
28 
29 void test2() {
30     using namespace std;
31 
32     int n, index;
33     while(cout << "Enter n and index: ", cin >> n >> index) {
34         try {
35             Vector<int> v(n, n);
36             v.at(index) = -999;
37             cout << "v: "; output(v);
38         }
39         catch (const exception &e) {
40             cout << e.what() << endl;
41         }
42     }
43 }
44 
45 int main() {
46     cout << "测试1: 模板类接口测试\n";
47     test1();
48 
49     cout << "\n测试2: 模板类异常处理测试\n";
50     test2();
51 }

运行结果截图: 

 任务5

task5.cpp

 1 #include <iostream>
 2 #include <fstream>
 3 #include <vector>
 4 #include <string>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8 struct Student {
 9     string id;      // 学号
10     string name;    // 姓名
11     string major;   // 专业
12     int score;      // 分数
13 };
14 
15 bool readData(const string& filename, vector<Student>& students) {
16     ifstream infile(filename);
17     if (!infile) {
18         cerr << "Error: Cannot open file " << filename << endl;
19         return false;
20     }
21     string header; 
22     getline(infile, header);
23 
24     Student temp;
25     while (infile >> temp.id >> temp.name >> temp.major >> temp.score) {
26         students.push_back(temp);
27     }
28 
29     infile.close();
30     return true;
31 }
32  
33 void writeData(const string& filename, const vector<Student>& students) {
34     ofstream outfile(filename);
35     if (!outfile) {
36         cerr << "Error: Cannot open file " << filename << endl;
37         return;
38     }
39 
40     outfile << "学号\t姓名\t专业\t分数\n";
41     for (const auto& s : students) {
42         outfile << s.id << "\t" << s.name << "\t" << s.major << "\t" << s.score << "\n";
43     }
44 
45     outfile.close();
46 }
47 bool compareStudents(const Student& a, const Student& b) {
48     if (a.major != b.major) return a.major < b.major; 
49     return a.score > b.score; 
50 }
51 
52 void printStudents(const vector<Student>& students) {
53     cout << "学号\t姓名\t专业\t分数\n";
54     for (const auto& s : students) {
55         cout << s.id << "\t" << s.name << "\t" << s.major << "\t" << s.score << endl;
56     }
57 }
58 
59 int main() {
60     vector<Student> students;
61 
62     if (!readData("data5.txt", students)) {
63         return 1;
64     }
65 
66     sort(students.begin(), students.end(), compareStudents);
67 
68     cout << "排序后的学生信息:\n";
69     printStudents(students);
70 
71     writeData("ans5.txt", students);
72     cout << "\n排序结果已保存到文件 ans5.txt" << endl;
73 
74     return 0;
75 }

运行结果截图:

 

 

 

标签:std,文件,const,index,get,Complex,实验,include,模板
From: https://www.cnblogs.com/rxt711/p/18610700

相关文章

  • 实验6
    任务4:#include<stdio.h>#defineN10typedefstruct{charisbn[20];//isbn号charname[80];//书名charauthor[80];//作者doublesales_price;//售价intsales_count;//销售册数}Book;voidou......
  • 24.11.11 文件权限
    rwx的含义rread#读catlessmorevimwwrite#写vimechosedxexcuter#可执行-#没有权限Linux是如何知道我对某个文件或目录有什么权限的?[root@oldboyedu~]#ll1总用量0-rw-r--r--1rootroot011月120:33fileA.txt-rw-r--r--1rootroot011月......
  • 实验6
    实验任务4:1#include<stdio.h>2#defineN1034typedefstruct{5charisbn[20];//isbn号6charname[80];//书名7charauthor[80];//作者8doublesales_price;//售价9intsales_count;......
  • 24.11.04 核心文件补充以及有关文件的常用命令
    运维人员的工作内容工作项目工作内容应急响应紧急故障案例,网站入侵故障,安全威胁,负载高/cpu,内存使用率高日常项目维护备份,安全加固,入侵检测,监控集群,容器化服务,上云(阿里云)架构巡检业务指标,系统架构,监控是否正常DevSecOps代码发布手动自动化上线DevOps,DevSecO......
  • 24.11.05 文件属性
    ubt下载zip和uznipapt-getinstallunzipzipLinux快捷键Ctrl+a#快速到开头,只针对行,不适用于vimCtrl+e#快速到最后,只针对行,不适用于vimctrl+c#中断进程检查baidu.com网站的80端口是否开启telnetbaidu.com80#只适用于ubt,不适用于麒麟系统查看系统,CPU,主机名,内......
  • 计算机组成原理——可控加减法电路实验【仅供参考】
    一、实验目的、要求实验目的熟悉一位全加器的结构理解并掌握补码加减法运算的原理及判溢方法要求需要掌握一位全加器如何实现的具体公式,在“一位全加器FA封装1”中,正确完成一位全加器的内部连接。在“8位可控加法减法器”中,使用已经封装的一位全加器进行串行连接,并在......
  • Windows系统下无头构建Linux系统下的so文件
     (开始执行以下步骤时,确保已经在系统下安装2017版Labview软件,及其驱动软件,压缩包内包含32位java插件安装包与NILinuxReal-TimeEclipseEdition的C/C++开发工具包***建议均使用默认路径安装***C盘空间配置大一些)1.首先我们需要在Windows系统里面安装Java插件(建议使用32位......
  • springboot毕设 计算机组成原理虚拟仿真实验系统程序+论文
    系统程序文件列表开题报告内容研究背景随着信息技术的飞速发展,计算机组成原理作为计算机科学与技术专业的重要基础课程,其教学方式的现代化与实验手段的多样化成为提升教学质量的关键。传统的教学模式依赖于实体硬件实验平台,存在资源有限、维护成本高、实验灵活性不足等问题......
  • 实验6 模板类、文件I/O和异常处理
    task4:Vector.hpp源代码:1#include<iostream>23usingnamespacestd;45template<typenameT>6classVector7{8public:9Vector(intnn):n{nn}{10if(n<0)throwlength_error("Vector:negativesize&quo......
  • 实验六
    任务四:1#include<stdio.h>2#defineN1034typedefstruct5{6charisbn[20];//isbn号7charname[80];//书名8charauthor[80];//作者9doublesales_price;//售价10intsales_count;//销售册数11}......