//问题描述: Define a struct Data to keep track of dates. Provide functions
// that read Dates from input, write Dates to output, and initialize a Date
// with a date.
//备注: 对输入日期的处理上容错能力不强。
//作者: 杨明哲
//完成日期: 2005-03-25
//BUG报告; dearymz@163.com
#include <cassert>
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
namespace ymz
{
//日期结构
struct Date
{
short year;//–32,768 to 32,767
short month;
short day;
};//注意这里的分号
//闰年的判断
int IsLeapYear(unsigned short year)
{
if((year%4==0&&year%100!=0)
|| year%400==0)
return 1;
else
return 0;
}
//得到某个月一共有几天
int DatePerMonth(short int year, short month)
{
assert(month <= 12 && month >=1);//注意月份的合法性范围
static unsigned short datePerMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(month != 2)//不是二月
{
return datePerMonth[month];
}
else if(IsLeapYear(year))//闰年二月
{
return datePerMonth[month] + 1;//29
}
else//平年二月
return datePerMonth[month];//28
}
//得到某个月一共有几天
int DatePerMonth(const Date& date)
{
return DatePerMonth(date.year, date.month);
}
void GetDate(ymz::Date* today)//对于要从参数传出计算结果的,建议使用指针而不是引用。
{
SYSTEMTIME time;//Windows Platform SDK: Windows System Information
GetSystemTime(&time);//调用Win API得到当前的时间。也可以利用DOS平台的相关函数
today->day = time.wDay;
today->month = time.wMonth;
today->year = time.wYear;
}
const int bufSize = 64;
//重载的输入运算符
istream& operator>>(istream& istr, ymz::Date& date)
{
date.day = date.month = date.year = -1;
//自动对输入进行解析
char c;
istr>>date.year>>c>>date.month>>c>>date.day;
//手工对输入进行解析
/*char buf[bufSize + 1];
char s[3][bufSize + 1];
istr.getline(buf, bufSize);
int current = 0;
int currentIndex = 0;
bool blank = true;
for(unsigned i = 0; i < bufSize && current < 3; i++)
{
char c = buf[i];
if(isdigit(c))//是数字
{
blank = false;
s[current][currentIndex] = c;
currentIndex++;
}
else//不是数字是分隔符
{
if(blank)
continue;
else
{
blank = true;
s[current][currentIndex] = '\0';
current++;
currentIndex = 0;
}
}
}
s[current][currentIndex] = '\0';
date.year = atoi(s[0]);
date.month = atoi(s[1]);
date.day = atoi(s[2]);*/
//错误检测
if( date.month <= 0 || date.month >12 ||
date.day <= 0 || date.day > ymz::DatePerMonth(date))
throw "输入的日期不合法!";
return istr;
}
//重载的输出运算符
ostream& operator<<(ostream& ostr, ymz::Date& date)
{
ostr<<date.year<<'-'<<date.month<<'-'<<date.day;
return ostr;
}
}
//测试函数
void main()
{
try
{
ymz::Date date;
ymz::GetDate(&date);//得到当前时间
cout<<"现在的时间是:"<<date<<endl;
cout<<"请输入一个新的时间以构造新的时间结构:"<<endl;
cin>>date;
cout<<"修改后的时间结构为:"<<date<<endl;
cin.get();
}
catch(char* ex)
{
cout<<ex<<'\a'<<endl;
}
catch(...)
{
cout<<"发生意外错误!"<<'\a'<<endl;
}
}
评论