Info.hpp
#include <iostream> #include <string> using namespace std; class Info { public: Info(string a, string b, string c, int d); void print() const; private: string nickname, contact, city; int n; }; Info::Info(string a, string b, string c, int d) : nickname{a}, contact{b}, city{c}, n{d} {} void Info::print() const { cout << "称呼: " << nickname << endl; cout << "联系方式: " << contact << endl; cout << "所在城市: " << city << endl; cout << "预定人数: " << n << endl; }
task5.cpp
#include "info.hpp" #include <iostream> #include <string> #include <vector> using namespace std; const int capacity = 100; vector<Info> audience_info_list; int main() { cout << "录入信息:" << endl; cout << endl; cout << "称呼/昵称,联系方式(邮箱/手机号),所在城市,预定参加人数" << endl; int d, now = 0; string a, b, c; while(cin >> a >> b >> c >> d) { Info temp(a, b, c, d); if(now + d <= capacity) { now += d; audience_info_list.push_back(temp); } else { cout << "对不起,只剩" << capacity - now << "个位置." << endl; cout << "1. 输入u, 更新(update)预定信息" << endl; cout << "2. 输入q, 退出预定" << endl; cout << "你的选择:"; char op; cin >> op; if(op == 'u') continue; else if(op == 'q') break; } } cout << "截至目前,一共有" << now << "位听众预定参加。预定听众信息如下:" << endl; for(auto const& obj : audience_info_list) obj.print(); return 0; }
TextCoder.hpp
#include <string> using namespace std; class TextCoder { public: TextCoder(string s) : text{s} {} string encoder(); string decoder(); private: string text; }; string TextCoder::encoder() { for(auto &ch : text) { if(ch >= 'a' && ch <= 'z') { ch += 5; if(ch > 'z') ch -= 'z' - 'a'; } else if(ch >= 'A' && ch <= 'Z') { ch += 5; if(ch > 'Z') ch -= 'Z' - 'A'; } } return text; } string TextCoder::decoder() { for(auto &ch : text) { if(ch >= 'a' && ch <= 'z') { ch -= 5; if(ch < 'a') ch += 'z' - 'a'; } else if(ch >= 'A' && ch <= 'Z') { ch -= 5; if(ch > 'Z') ch += 'Z' - 'A'; } } 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输入英文文本: "; } }
之前一直以为标准库里的vector、array、string、迭代器等十分难上手,没有接触,现在发现十分好用,配合auto变量能让代码变得简洁易懂,以后要经常使用。