#include <iostream> using namespace std;
struct date { int year; int month; int day; }older,later;
int day[2][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31}, {0,31,29,31,30,31,30,31,31,30,31,30,31}};
int account() { int sum=0; int i=0; int month=0; int leap_o,leap_l;
for (i=older.year ; i<later.year ;i++) //lesved middle years count
{ if (i%4==0 && i%100!=0 || i%400==0) sum+=366; else sum+=365; }
leap_o=older.year%4==0 && older.year%100!=0 || older.year%400==0; leap_l=later.year%4==0 && later.year%100!=0 || later.year%400==0;
if (sum!=0) //in the different years
{ if (later.year - older.year ==1) { for (i=1;i<older.month;i++) sum-=day[leap_o][i]; sum-=older.day;
for (i=1;i<later.month;i++) sum+=day[leap_l][i]; sum+=later.day; } } else //in the same year
{ if (older.month != later.month) { for (i=older.month+1 ; i<later.month ; i++) sum+=day[leap_l][i]; sum+=(day[leap_o][older.month]-older.day); sum+=day[leap_l][later.month]; } else sum+=(later.day-older.day); }
return sum; }
int todate(char line[],int i) { int state=0;//It shows what means about the '.'
int pointer=0; int sum=0;
while (line[pointer]!='\n') { if (line[pointer]!='.') { sum=sum*10+line[pointer]-'0'; } else { switch (state) { case 0:if (i==1) { older.year=sum; sum=0; } else { later.year=sum; sum=0; } state++; break; case 1: if (sum>12) return -1; if (i==1) { older.month = sum; sum=0; } else { later.month = sum; sum=0; } state++; break; } } pointer++; } if (state == 2) { if (sum>31) return -1; if (i==1) { older.day = sum; sum=0; } else { later.day = sum; sum=0; } } if (state!=2) return -1; return 0; }
int enter(char line[],int k) { char c; int i=0; int dot=1; //Below I may solve the problem about keybord buffer.
while ((c=getchar())!='\n') { if (i>10) { i=0; } line[i++]=c; } line[i]='\n'; i=0;
while (line[i]!='\n') { if (line[i]<='9'&&line[i]>='0'||line[i]=='.') { if (line[i]=='.') dot++; if (dot >3) return -1; } else return -1; i++; }
i=todate(line,k);
return i; }
void main() { char line[11]; int sum_day=0;
cout <<"Please enter the older date:";
while (enter (line,1)==-1) { cout <<"Date Error!!"<<endl; cout <<"Please reenter:"; }
cout <<"Please enter the later date:";
while (enter (line,2)==-1) { cout <<"Date Error!!"<<endl; cout <<"Please reenter:"; }
sum_day=account(); if (sum_day<0) cout <<"Error!!"<<endl; else cout <<"The sum of the day is "<<sum_day<<endl; }
|