实验二 数组、指针与C++标准库
任务五:
//Info.hpp
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 5 class Info{ 6 private: 7 string nickname; 8 string contact; 9 string city; 10 int n; 11 public: 12 Info(string nickname0 = "*", string contact0 = "*", string city0 = "*", int n0 = 0): 13 nickname(nickname0), contact(contact0), city(city0), n(n0) {} 14 void print(){ 15 cout << "称呼: " << nickname << endl; 16 cout << "联系方式: " << contact << endl; 17 cout << "所在城市: " << city << endl; 18 cout << "预定人数: " << n << endl; 19 } 20 };
//5.cpp
1 #include"Info.hpp" 2 #include<iostream> 3 #include<vector> 4 5 int main(){ 6 using namespace std; 7 8 const int capacity = 100; 9 vector<Info> audience_info_list; 10 int number = 0; 11 12 string nickname, contact, city; 13 int n; 14 cout << "录入信息:" << endl; 15 cout << "称呼/昵称,联系方式(邮箱/手机号),所在城市,预定人数:" << endl; 16 while(cin >> nickname){ 17 int flag = 0; 18 cin >> contact >> city >> n; 19 Info t{nickname, contact, city, n}; 20 if(number + n > capacity){ 21 char x; 22 cout << "对不起,只剩" << capacity-number << "个位置" << endl; 23 cout << "1.输入u,更新(update)预定信息" << endl; 24 cout << "2.输入q,退出预定" << endl; 25 cout << "您的选择是:" << endl; 26 cin >> x; 27 switch(x){ 28 case 'u': 29 flag = 1; 30 break; 31 case 'q': 32 flag = 2; 33 break; 34 default: 35 flag = 2; 36 cout << "输入错误,已为您退出预定"; 37 break; 38 } 39 } 40 if(flag == 2) 41 break; 42 else if(flag == 0){ 43 number += n; 44 audience_info_list.push_back(t); 45 } 46 } 47 48 cout << "截止目前,一共有" << number << "位听众预定参加。预定观众信息如下:" << endl; 49 for(auto it = audience_info_list.begin(); it != audience_info_list.end(); ++it) 50 it->print(); 51 }
运行结果:
任务六:
//TextCoder.hpp
#include<iostream> #include<cstring> using namespace std; class TextCoder{ private: string text; public: TextCoder(string t): text(t){} string encoder(); string decoder(); }; string TextCoder::encoder(){ int len = text.length(); for(int i=0; i<len; i++){ char x = text[i]; if((x>='a'&&x<='u')||(x>='A'&&x<='U')){ text[i] += 5; } else if((x>='v'&&x<='z')||(x>='V'&&x<='Z')){ text[i] -= 21; } } return text; } string TextCoder::decoder(){ int len = text.length(); for(int i=0; i<len; i++){ char x = text[i]; if((x>='f'&&x<='z')||(x>='F'&&x<='Z')){ text[i] -= 5; } else if((x>='a'&&x<='e')||(x>='A'&&x<='Z')){ text[i] += 21; } } return text; }
//task6.cpp
#include "textcoder.hpp" #include <iostream> #include <string> int main() { using namespace std; string text, encoded_text, decoded_text; cout << "输入英文文本: "; while (getline(cin, text)) { encoded_text = TextCoder(text).encoder(); // 这里使用的是临时无名对象 cout << "加密后英文文本:\t" << encoded_text << endl; decoded_text = TextCoder(encoded_text).decoder(); // 这里使用的是临时无名对象 cout << "解密后英文文本:\t" << decoded_text << endl; cout << "\n输入英文文本: "; } }
运行结果截图: