主题:[讨论]跪求!!解答关于C语言的日期输入的问题...
yuyong87394634
[专家分:0] 发布于 2011-06-20 22:08:00
从键盘输入销售日期(格式为YY-MM-DD) 判断日期的格式是否合法时,需要判断长度是否为10,第5位和第8位是否为’-’,字符,将1-4位表示的年份,6-7位表示的月份,9-10位表示的日期分别转换成整数。判断是否满足构成日期的条件闰年月份只能是1-12之间的数,如果是闰年,二月可以是29天否则不能大于28,1,3,5,7,8,10,12月可以是31天,其余只能小于等于30.
(这个程序便于以后进行日期范围的销售查询)
C语言新手跪谢!!!
回复列表 (共3个回复)
沙发
fragileeye [专家分:1990] 发布于 2011-06-21 09:54:00
有点想不通,lz对这T的理解比较清晰了,为何。。
帖上一段供lz参考吧。
[code=c]
#include <stdio.h>
#define MAX 11
#define MONTH 13
#define TRUE 1
#define FALSE 0
const int Month_Leap[MONTH] =
{
0,
31, 29, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31
};
const int Month_No_Leap[MONTH] =
{
0,
31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31
};
int judge_str(char *str);
int main(int argc, char *argv[])
{
char str[MAX];
while(1)
{
fgets(str, sizeof(str), stdin);
if(judge_str(str) == TRUE)
{
printf("Datas're legal.\n");
break;
}
else
{
printf("Datas're illegal! please retry it!\n");
}
}
return 0;
}
int judge_str(char *str)
{
char *p = NULL;
int index ,ct , year, month, day;
year = month = day = 0;
for(ct = 0, p = str, index = 0; p[index] != '\0'; ct++, index++)
{
if(index == 4 || index == 7) //判断字符'-'的要求
{
if(p[index] != '-')
{
return FALSE ;
}
}
else if(p[index] < '0' || p[index] > '9') //判断年月日在串中是否为数字
{
return FALSE ;
}
if(index < 4) //得到年月日
{
year = year * 10 + p[index] - '0';
}
else if(index >= 5 && index < 7)
{
month = month * 10 + p[index] - '0';
}
else if(index >= 8)
{
day = day * 10 + p[index] - '0';
}
}
if(ct < MAX - 1)
{
return FALSE;
}
else
{
if(month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) //闰年时2月的要求
{
if(day > Month_Leap[month])
{
return FALSE;
}
}
else if(day > Month_No_Leap[month]) //某月与该月总天数的要求
{
return FALSE ;
}
}
return TRUE ;
}
[/code]
板凳
eastcowboy [专家分:25370] 发布于 2011-06-21 23:28:00
C语言有不少的函数,都可以巧妙地利用起来。
[code=c]#include <time.h>
#include <stdio.h>
#include <string.h>
int main()
{
char input[100];
int count;
int year, month, day;
struct tm tm;
// 输入
if (!fgets(input, sizeof(input) - 1, stdin))
{
printf("输入错误\n");
return 0;
}
// 是否符合XXXX-XX-XX的形式?(X表示一个数字)
count = 0;
if (sscanf(input, "%*4[0-9]-%*2[0-9]-%*2[0-9]%n", &count) < 0 || count != 10)
{
printf("不合法\n");
return 0;
}
// 符合,则把年、月、日分别保存到变量中
(void)sscanf(input, "%d-%d-%d", &year, &month, &day);
// 填入到结构体,看看是否能成功的执行mktime
// 若能,且日期符合,说明合法,否则不合法
memset(&tm, 0, sizeof(tm));
tm.tm_year = year - 1900;
tm.tm_mon = month;
tm.tm_mday = day;
if (mktime(&tm) > 0 &&
tm.tm_year == year - 1900 &&
tm.tm_mon == month &&
tm.tm_mday == day)
{
printf("合法\n");
}
else
{
printf("不合法\n");
}
return 0;
}[/code]
3 楼
fragileeye [专家分:1990] 发布于 2011-06-22 13:33:00
if (sscanf(input, "%*4[0-9]-%*2[0-9]-%*2[0-9]%n", &count) < 0 || count != 10)
{
printf("不合法\n");
return 0;
}
--------------------------------------------------
PL。
我来回复