📄 wex3_10.cpp
字号:
#include <iostream.h>
#include <string.h>
#include <strstream.h>
#include <stdlib.h>
class Date
{
private:
// private members that specify the date
int month, day, year;
public:
// constructors. default date is January 1, 1900
Date (int m = 1, int d = 1, int y = 0);
Date (char *dstr);
// output the date in the format "month day, year"
void PrintDate (void);
Date IncrementDate(int n) const;
};
// constructor. month, day, year given as integer values mm dd yy
Date::Date (int m, int d, int y) : month(m), day(d)
{
year = 1900 + y; // y is a year in the 20th century
}
// constructor. month, day, year given as string "mm/dd/yy"
Date::Date (char *dstr)
{
char inputBuffer[16];
char ch;
// copy string to inputBuffer and declare an array based input stream
strcpy(inputBuffer,dstr);
istrstream input(inputBuffer, sizeof(inputBuffer));
// read from input stream. use ch to read the '/' characters
input >> month >> ch >> day >> ch >> year;
year += 1900;
}
// print date with full month name.
void Date::PrintDate (void)
{
// allocate static array of month names. Index 0 is NULL string.
static char *Months[] = {"","January","February","March","April",
"May","June", "July","August", "September",
"October","November","December"};
cout << Months[month] << " " << day << ", " << year;
}
int IsLeapYear(int y)
{
if (y % 4 != 0 || (y % 100 == 0 && y % 100 != 0))
return 0;
else
return 1;
}
Date Date::IncrementDate(int n) const
{
int tempday;
int daysInMonth[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
Date d(month,day,year-1900); // has same date as current object
if (n < 0 || n > 365)
{
cerr << "Increment " << n << " is out of range" << endl;
exit(1);
}
if (month > 1) // current month after January
{
if (IsLeapYear(year+1))
daysInMonth[2] = 29; // next year is a leap year
}
else
if (IsLeapYear(year))
daysInMonth[2] = 29; // current year is a leap year
tempday = day + n;
while(tempday > daysInMonth[d.month])
{
tempday -= daysInMonth[d.month];
if(d.month != 12) // current month not December
d.month++;
else
{
d.year++;
d.month = 1; // set month to January of next year
}
}
d.day = tempday;
return d;
}
void main(void)
{
Date d1(1,10,92), d2(1,10,93), d3(12,1,92), d4(12,1,91);
Date d;
d = d1.IncrementDate(50); d.PrintDate(); cout << endl;
d = d2.IncrementDate(50); d.PrintDate(); cout << endl;
d = d3.IncrementDate(91); d.PrintDate(); cout << endl;
d = d4.IncrementDate(91); d.PrintDate(); cout << endl;
}
/*
<Run>
February 29, 1992
March 1, 1993
March 2, 1993
March 1, 1992
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -