9.51 设计一类,它又三个unsigned成员,分别表示年月日。为其编写构造函数,接受一个表示日期的string参数。
程序如下:
#include<iostream>
#include<string>
using namespace std;
class My_Date
{
public:
My_Date(const string &s);
unsigned year;
unsigned month;
unsigned day;
};
My_Date::My_Date(const string &s)
{
unsigned format=0;
if(s.find_first_of("/")!=string::npos)
format=0x10;
if(s.find_first_of(",")!=string::npos)
format=0x01;
switch(format)
{
case 0x10:
day=stoi(s.substr(0,s.find_first_of("/")));
month=stoi(s.substr(s.find_first_of("/")+1,s.find_last_of("/")-s.find_first_of("/")));
year=stoi(s.substr(s.find_last_of("/")+1,4));
break;
case 0x01:
day=stoi(s.substr(s.find_first_of("0123456789"),s.find_first_of(",")-s.find_first_of("0123456789")));
if(s.find("Jan")<s.size()) month=1;
if(s.find("Feb")<s.size()) month=2;
if(s.find("Mar")<s.size()) month=3;
if(s.find("Apr")<s.size()) month=4;
if(s.find("May")<s.size()) month=5;
if(s.find("Jun")<s.size()) month=6;
if(s.find("Jul")<s.size()) month=7;
if(s.find("Aug")<s.size()) month=8;
if(s.find("Sep")<s.size()) month=9;
if(s.find("Oct")<s.size()) month=10;
if(s.find("Nov")<s.size()) month=11;
if(s.find("Dec")<s.size()) month=12;
year=stoi(s.substr(s.find_last_of(",")+1,4));
break;
}
}
int main()
{
My_Date d("99/21/1234");
cout<<d.day<<" "<<d.month<<" "<<d.year<<endl;
return 0;
}
运行结果如下:
原文:http://www.cnblogs.com/wuchanming/p/3915244.html