#include <iostream>
#include <string>
#include "date.h"
using namespace std;
int main()
{
string dates[]{"Jan 1,2014", "February 1 2014", "3/1/2014"};
try
{
for (auto ds : dates)
{
date d1(ds);
cout << d1;
}
}
catch (invalid_argument e)
{
cout << e.what() << endl;
}
system("pause");
return 0;
}
#ifndef DATE_H_
#define DATE_H_
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
class date
{
public:
friend ostream &operator<<(ostream & os, const date & d);
date() = default;
date(string &ds);
unsigned y()const { return year; }
unsigned m()const { return month; }
unsigned d()const { return day; }
private:
unsigned year, month, day;
};
const string month_name[]{"January", "February", "March", "april", "May", "June", "July", "August", "September", "October", "November", "December"};
const string month_abbr[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"};
const int days[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int get_month(string &ds, int &end_of_month)
{
int i, j;
for (i = 0; i < 12; ++i)
{
for (j = 0; unsigned(j) < month_abbr[i].size();++j)
if (ds[j]!=month_abbr[i][j])
break;
if (j == month_abbr[i].size())
break;
}
if (i == 12)
throw invalid_argument("不是合法的月份名");
if(ds[j]==' ')
{
end_of_month = j + 1;
return i + 1;
}
for (; unsigned(j) < month_name[i].size(); ++j)
if (ds[j] != month_name[i][j])
break;
if (j == month_name[i].size() && ds[j] == ' ')
{
end_of_month = j + 1;
return i + 1;
}
throw invalid_argument("不是合法月份名");
}
int get_day(string &ds, int month, int &p)
{
size_t q;
int day = stoi(ds.substr(p), &q);
if (day<1 || day>days[month])
throw invalid_argument("不是合法的月份值");
p += q;
return day;
}
int get_year(string &ds, int &p)
{
size_t q;
int year = stoi(ds.substr(p), &q);
if (p + q < ds.size())
throw invalid_argument("非法结尾内容");
return year;
}
date::date(string &ds)
{
int p;
size_t q = 0;
if ((p = ds.find_first_of("0123456789")) == string::npos)
throw invalid_argument("没有数字非法日期");
if (p > 0)
{
month = get_month(ds, p);
day = get_day(ds, month, p);
if (ds[p] != ' '&&ds[p] != ',')
throw invalid_argument("非法间隔符");
++p;
year = get_year(ds, p);
p = q;
}
else
{
month = stoi(ds, &q);
p = q;
if (month < 1 || month>12)
throw invalid_argument("不是合法月份值");
if (ds[p++] != '/')
throw invalid_argument("非法间隔符");
if (ds[p++] != '/')
throw invalid_argument("非法间隔符");
year = get_year(ds, p);
}
}
ostream &operator<<(ostream & os, const date & d)
{
os << d.y() << "年" << d.m() << "月" << d.d() << "日" << endl;
return os;
}
#endif // !DATE_H_