primer C++ 9.5.5练习 9.5.1题

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值