C++ Primer——编写较健壮的构造函数

题目:设计一个类,它又三个unsigned成员,分别表示年、月和日。为其编写构造函数,接受一个表示日期的string参数,你的构造函数应该能处理不同的数据格式,如January 1,1990、1/1/1990、Jan 1 1990等

#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Date 
{
	friend void print(Date& item);
private:
	unsigned year;
	unsigned month;
	unsigned date;
public:	
	Date(const string& s);
	unsigned change_to_digit(const string& s);
};
unsigned Date::change_to_digit(const string& s)
{
	string numbers{ "0123456789" };
	if (s.find_first_of(numbers) != string::npos)
		return stoi(s);
	vector<string> v{ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
	decltype(v.size()) loc = 0;
	for (decltype(v.size()) i = 0; i != v.size(); ++i)
		if (s.find(v[i]) != string::npos)
		{
			loc = i + 1;	break;
		}
	return loc;
}
Date::Date(const string& s)
{
	string punct{ " /," };
	auto pos = s.find_first_of(punct);
	month = change_to_digit(s.substr(0, pos));   
	++pos;
	auto pos2 = s.find_first_of(punct, pos);
	date = stoi(s.substr(pos, pos2 - pos));
	++pos2;
	auto pos3 = s.find_first_of(punct, pos2);
	year= stoi(s.substr(pos2, pos3 - pos2));
}

void print(Date& item)
{
	cout << item.year << " " << item.month << " " << item.date << endl;
}
int main()
{
	Date date1("January 1,1990");
	print(date1);
	Date date2("1/1/1990");
	print(date2);
	Date date3("Jan 1 1990");
	print(date3);
	system("pause");
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值