实验二 数组,指针与c++标准库
#ifndef Info_hpp #define Info_hpp #include<iostream> using namespace std; class Info{ public: Info(); Info(string nickname0,string contact0,string city0,int n0); ~Info(); void print(); private: string nickname; string contact; string city; int n; static int count; }; int Info::count=0; Info::Info(){ } Info::Info(string nickname0,string contact0,string city0,int n0){ nickname=nickname0; contact=contact0; city=city0; n=n0; } Info::~Info(){ } void Info::print() { cout<<"称呼: "<<nickname<<endl; cout<<"联系方式: "<<contact<<endl; cout<<"所在城市: "<<city<<endl; cout<<"预定人数: "<<n<<endl; } #endif
#include"Info.hpp" #include<iostream> #include<string> #include<vector> const int capacity=100; static int count=0; int main() { vector<Info> audience_info_list; string nickname0,contact0,city0; int n0; Info s; char c; cout<<"录入信息:"<<endl<<endl; cout<<"称呼/昵称,联系方式(邮箱/手机号),所在城市,预定参加人数"<<endl; while(cin>>nickname0>>contact0>>city0>>n0) { int temp=count; s=Info(nickname0,contact0,city0,n0); if(temp+n0<=capacity) { count+=n0; audience_info_list.push_back(s); } else { cout<<"对不起,只剩"<<capacity-count<<"个位置。"<<endl; cout<<"1.输入u,更新(update)预定信息"<<endl; cout<<"2.输入q,推出预定"<<endl; cout<<"你的选择:" ; cin>>c; if(c=='q') break; } } cout<<endl; cout<<"截至目前,一共有"<<count<<"位听众预定参加。预定参加人数如下:"<<endl; for(auto x:audience_info_list) x.print(); return 0; }



#ifndef TextCoder_hpp #define TextCoder_hpp #include<iostream> #include<string> using namespace std; class TextCoder{ public: TextCoder(); TextCoder(string text0); string encoder(); string decoder(); private: string text; }; TextCoder::TextCoder(){ } TextCoder::TextCoder(string text0){ text=text0; } string TextCoder::encoder(){ for(auto &c:text) { if(c>='a'&&c<='u') c+=5; else if(c>'u'&&c<='z') c='a'+5-('z'-c+1); else if(c>='A'&&c<='U') c+=5; else if(c>'U'&&c<='Z') c='A'+5-('Z'-c+1); } return text; } string TextCoder::decoder(){ for(auto &c:text) { if(c<='z'&&c>='f') c-=5; else if(c>='a'&&c<'f') c='z'-5+(c-'a'+1); else if(c<='Z'&&c>='F') c-=5; else if(c>='A'&&c<'F') c='z'-5+(c-'A'+1); } return text; } #endif
#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输入英文文本: "; } }

实验总结:
本次实验要着重掌握string,vector和array的用法。首先要记住它们的常用函数和特性。string和普通字符串数组相比更加方便也更加安全。可以像使用基本数据类型一样赋值,复制,比较,输入输出以及+来连接。同时也可以像数组那样通过下标访问。vector适用于数据个数无法确定的场合。通过push_back()和pop_back()可以很方便的对尾部进行操作。
另外学习了for语句新的遍历方式,如string(auto c:s)或string(auto &c:s),其中&c是引用,而c则是创建了一个新的string。

浙公网安备 33010602011771号