#include<stdio.h> #include<stdlib.h> #include<string.h> //检查日期函数_声明 int checkDate(Date date); int main() { int check=0; Date date; do { printf("请输入一个日期(格式为YYYY-MM-DD):\n"); printf("位数不足不补零#\n"); scanf("%d-%d-%d",&date.year ,&date.month,&date.day); check=checkDate(date); }while(check!=1); printf("日期正确!\n"); system("pause"); return 0; }
定义一个结构体变量,存放日期
typedef struct Date { int year; int month; int day; }Date;
然后定义一个判断日期合法性的函数
//检查日期函数_定义 int checkDate(Date date) { int check=0; //年份判断 if(date.year<1900 || date.year>2100) { printf("年份错误!\n"); return check; } //月份判断 if(date.month<1 || date.month>12) { printf("月份错误!\n"); return check; } int a=date.year; int m=date.month; //若为闰年,28天 if ((a%4==0 && a%100!=0) || (a%400==0)) { if(date.month==2 && date.day<=28 && date.day>=1) { printf("闰年日期错误!\n"); return check; } } int judge=-1; //普通日期判断(1-31 0-30 -1-29) switch(m) { case 1: judge=1; break; case 2: judge=-1; break; case 3: judge=1; break; case 4: judge=0; break; case 5: judge=1; break; case 6: judge=0; break; case 7: judge=1; break; case 8: judge=1; break; case 9: judge=0; break; case 10: judge=1; break; case 11: judge=0; break; case 12: judge=1; break; } if((judge==1 && (date.day>31 || date.day<1)) || (judge==0 && (date.day>30 || date.day<1)) || (judge==-1 && (date.day>29 || date.day<1))) { printf("日期错误!\n"); return check; } check=1; return check; }