文档详情

数组指针与字符串.ppt

发布:2016-11-26约3.09万字共165页下载文档
文本预览下载声明
* * * * * * * * * * * *************************2013/11/12 * * * * * * * * * * * * * 例6-23 string类应用举例 * #include string #include iostream using namespace std; //根据value的值输出true或false,title为提示文字 inline void test(const char *title, bool value) { cout title returns (value ? true : false) endl; } 6.6 字符串 —— 6.6.2 string类 例6-23 (续) * int main() { string s1 = DEF; cout s1 is s1 endl; string s2; cout Please enter s2: ; cin s2; cout length of s2: s2.length() endl; //比较运算符的测试 test(s1 = \ABC\, s1 = ABC); test(\DEF\ = s1, DEF = s1); //连接运算符的测试 s2 += s1; cout s2 = s2 + s1: s2 endl; cout length of s2: s2.length() endl; return 0; } 6.6 字符串 —— 6.6.2 string类 用getline输入整行字符串 * 输入整行字符串 用cin的操作符输入字符串,会以空格作为分隔符,空格后的内容会在下一回输入时被读取 用string头文件中的getline可以输入整行字符串,例如: getline(cin, s2); 以其它字符作为分隔符输入字符串 输入字符串时,可以使用其它分隔符作为字符串结束的标志(例如逗号、分号) 把分隔符作为getline的第3个参数即可,例如: getline(cin, s2, ,); 6.6 字符串 —— 6.6.2 string类 例6-24 用getline输入字符串 * include iostream #include string using namespace std; int main() { for (int i = 0; i 2; i++) { string city, state; getline(cin, city, ,); getline(cin, state); cout City: city “ State: state endl; } return 0; } 6.6 字符串 —— 6.6.2 string类 运行结果: Beijing,China City: Beijing State: China San Francisco,the United States City: San Francisco State: the United States 6.7 综合实例——个人银行账户管理程序 改用字符串来表示银行账号 多个账户组织在一个数组中,这样可以把需要对各个账户做的事情放在循环中,避免了代码的冗余。 将日期用一个类来表示,内含年、月、日三个数据成员,同时设计计算相差天数 整个程序分为5个文件:date.h是日期类头文件,date.cpp是日期类实现文件,account.h是储蓄账户类定义头文件,account.cpp是储蓄账户类实现文件,6_25.cpp是主函数文件。 * //date.h #ifndef __DATE_H__ #define __DATE_H__ class Date { //日期类 private: int year; //年 int month; //月 int day; //日 int totalDays; //该日期是从公元元年1月1日开始的第几天 public: Date(int year, int month, int day); //用年、月、日构造日期 int getYear() const { return year; } int getMonth() const { return month; } int getDay() const { return day; } int getMaxDay() const; //获得当月有多少天 * 6.7 综合实例——个人银行账户管理程序 例6-25 bool isLeapYear() const { //判断当年是否为闰年
显示全部
相似文档