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=;
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(,s.find_first_of("/")));
month=stoi(s.substr(s.find_first_of("/")+,s.find_last_of("/")-s.find_first_of("/")));
year=stoi(s.substr(s.find_last_of("/")+,));
break;
case 0x01:
day=stoi(s.substr(s.find_first_of(""),s.find_first_of(",")-s.find_first_of("")));
if(s.find("Jan")<s.size()) month=;
if(s.find("Feb")<s.size()) month=;
if(s.find("Mar")<s.size()) month=;
if(s.find("Apr")<s.size()) month=;
if(s.find("May")<s.size()) month=;
if(s.find("Jun")<s.size()) month=;
if(s.find("Jul")<s.size()) month=;
if(s.find("Aug")<s.size()) month=;
if(s.find("Sep")<s.size()) month=;
if(s.find("Oct")<s.size()) month=;
if(s.find("Nov")<s.size()) month=;
if(s.find("Dec")<s.size()) month=;
year=stoi(s.substr(s.find_last_of(",")+,));
break;
}
}
int main()
{
My_Date d("99/21/1234");
cout<<d.day<<" "<<d.month<<" "<<d.year<<endl;
return ;
}

运行结果如下:

stoi的例子-LMLPHP

05-06 18:24