我试图将日期采用
dd/mm/yy
格式,但是当我这样写时,它会为我提供 191/033/0
的输出,用于 19/07/14
输入。
#include <stdio.h>
int main(){
int d1, d2, m1, m2, year;
printf("Enter date (dd/mm/yy): ");
scanf("%d,%d/%d,&,d/%d", &d1,&d2,&m1,&m2,&year);
return 0;
}
我该如何解决这个问题?
# include <stdio.h>
int main(){
int d, m, year;
printf("Enter date (dd/mm/yy): ");
scanf("%d/%d/%d", &d,&m,&year);
if (d%10==1 && d!=11) printf("%d st",d);
else if (d%10==2 && d!=12) printf("%d nd",d);
else if (d%10==3 && d!=13) printf("%d rd",d);
else printf("%d th",d);
return 0;
}
顺便说一句,
dd/mm/yy
不意味着“两天、两个月和两年”。这意味着“两位数字代表日、月和年”。这就是为什么你不需要那么多变量。
您需要
strftime()
功能,并正确处理输入,以免发生意外情况
这是如何操作的示例
#include <stdio.h>
#include <time.h>
#include <string.h>
int main()
{
char buffer[100];
struct tm date;
memset(&date, 0, sizeof(date));
printf("Enter date (dd/mm/yy): ");
if (fgets(buffer, sizeof(buffer), stdin) == NULL)
return -1;
if (sscanf(buffer, "%d/%d/%d", &date.tm_mday, &date.tm_mon, &date.tm_year) == 3)
{
const char *format;
format = "Dated %A %dth of %B, %Y";
if (strftime(buffer, sizeof(buffer), format, &date) > sizeof(buffer))
fprintf(stderr, "there was a problem converting the string\n");
else
fprintf(stdout, "%s\n", buffer);
}
return 0;
}