实验任务5
Info.cpp文件源码:
#include <iostream> #include <string> #include <vector> using namespace std; class Info { public: Info(string NICKNAME, string CONTACT, string CITY, int N) : nickname(NICKNAME), contact(CONTACT), city(CITY), n(N) {} ~Info() = default; void print() { cout << "称呼:\t\t" << nickname << endl; cout << "联系方式:\t" << contact << endl; cout << "所在城市:\t" << city << endl; cout << "预定人数:\t" << n << endl; } private: string nickname; string contact; string city; int n; };
task5.cpp源码:
#include <iostream> #include <string> #include <vector> #include "Info.cpp" using namespace std; const int capacity = 100; int main() { vector<Info>audience_info_list; string NICKNAME, CONTACT, CITY; int N, i = 0, sum = 0; cout << "录入信息:\n\n"; cout << "称呼/昵称,联系方式(邮箱/手机号),所在城市,预定参加人数;\n"; while (cin >> NICKNAME) { cin >> CONTACT; cin >> CITY; cin >> N; if (sum + N > capacity) { char flag; cout << "对不起,只剩下" << (capacity - sum) << "个位置。\n"; cout << "1、输入u,更新(update)预定信息\n" << "2、输入q,退出预定\n" << "你的选择:\t"; cin >> flag; if (flag == 'q') break; if (flag == 'u') { cout << "重新输入预定信息:\n"; continue; } } sum += N; Info temp(NICKNAME, CONTACT, CITY, N); audience_info_list.push_back(temp); i++; } cout << "截至目前,一共有" << sum << "位听众预约参加。预定听众信息如下:\n"; for (int j = 0; j < i; j++) { audience_info_list[j].print(); } }
编译演示:
实验任务6
TextCoder.hpp文件源码:
#include <iostream> #include <string> using namespace std; class TextCoder { public: TextCoder(string temp) : text(temp) {} ~TextCoder() = default; string encoder() { for (int i = 0; i < text.size(); i++) { if (text[i] <= 'u' && text[i] >= 'a') { text[i] += 5; continue; } if (text[i] <= 'z' && text[i] >= 'v') { text[i] = 'a' + (4 + static_cast<int>(text[i] - 'z')); continue; } if (text[i] <= 'U' && text[i] >= 'A') { text[i] += 5; continue; } if (text[i] <= 'Z' && text[i] >= 'V') { text[i] = 'A' + (4 + static_cast<int>(text[i] - 'Z')); continue; } } return text; } string decoder() { for (int i = 0; i < text.size(); i++) { if (text[i] <= 'z' && text[i] >= 'f') { text[i] -= 5; continue; } if (text[i] <= 'e' && text[i] >= 'a') { text[i] = 'z' - (4 - static_cast<int>(text[i] - 'a')); continue; } if (text[i] <= 'Z' && text[i] >= 'F') { text[i] -= 5; continue; } if (text[i] <= 'E' && text[i] >= 'A') { text[i] = 'Z' - (4 - static_cast<int>(text[i] - 'A')); continue; } } return text; } private: string 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输入英文文本: "; } }
编译演示:
实验总结:1、vector类的使用,不能越界;2、在赋值前,不要对vector类的对象使用下标;