9.5.1 :设计日期类 通过传入string初始化类成员。
写了挺长时间,尽量运用了近几章所学,作为复习题很有效果。
/*****************
primerC++ practice 9.5.5-9.51
narcissu,2018
****************/
/* date.h
*/
#ifndef DATE_H
#define DATE_H
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
class Date {
private:
unsigned long year{ 0 },
month{ 0 },
day{ 0 };
std::vector<std::string> vstr{ "january","february","march","april","may","june","july","august","september","october","november","december" };//查找词源
std::string vstr2{"1234567890"};//所有数字
public:
Date() = default;//默认构造函数
Date(std::string inps);//目标构造函数
};
#endif
Date::Date(std::string inps) {
std::transform(inps.begin(), inps.end(), inps.begin(), ::tolower);//大小写转换
int index = 0;
string::size_type sindex;
for (auto decl : vstr) {//循环搜索月份单词 若找到则将查找次数存入month作为月份并移除单词及后一位字符
if ((sindex = inps.find(decl) )!= string::npos) {
month = index + 1;
inps.erase(sindex, decl.size()+1);
break;
}
++index;
}
if (index == 12) {//若不存在月份单词则将第一个特殊符号位之前的部分转换成ul类型存入month
index = inps.find_first_not_of(vstr2);
string ds(inps, 0,index);
month = std::stoul(ds);
inps.erase(0, index+1);
}
index = 0;
//处理剩余部分,运用isstream以空格为间隔符读取并转换为ul类型数存入对应类成员
while ((index = inps.find_first_not_of(vstr2,index)) != string::npos) {
inps.erase(index, 1);
inps.insert(index, " ");
index += 1;
}
std::istringstream iss(inps);
std::string str1, str2;
iss >> str1 >> str2;
day = std::stoul(str1);
year = std::stoul(str2);
cout << month << " " << day << " " << year<<endl;//输出以测试结果
}
/*
progmain.cpp
main()主函数部分 其他省略
*/
int main(int argc, char *argv[]) {
Date d1("12/12/1988");//直接传参
system("pause");
return EXIT_SUCCESS;
}