日期格式dd.mm.yyyy in C
我想知道是否有办法从控制台读取日期格式为dd.mm.yyyy格式。我有一个结构,其中包含日期信息。 我尝试了另一种结构只是为了日期,月份和年份:
typedef struct { int day; int month; int year; } Date;
但点是个问题。 任何的想法?
尝试:
Date d; if (scanf("%d.%d.%d", &d.day, &d.month, &d.year) != 3) error();
您可以使用strptime()
将任意格式化的日期字符串读入struct tm
。
#define _XOPEN_SOURCE /* glibc2 needs this to have strptime(). */ #include #include #include #include ... Date d = {0}; char * fmt = "%d.%m.%Y"; char s[32] = ""; char fmt_scanf[32] = ""; int n = 0; sprintf(fmt_scanf, "%%%ds", sizeof(s) - 1); /* Created format string for scanf(). */ errno = 0; if (1 == (n = scanf(fmt_scanf, s))) { struct tm t = {0}; char * p = strptime(s, fmt, &t); if ((s + strlen(s)) != p) { fprintf(stderr, "invalid date: '%s'\n", s); } else { d.day = t.tm_mday; d.month = t.tm_mon + 1; /* tm_mon it zero-based. */ d.year = t.tm_year + 1900; /* tm_year is years since 1900. */ } } else { perror("scanf()"); }
更新 :
这种方式的积极副作用和额外收益是:
- 不需要输入validation,因为它全部由
strptime()
。 - 更改输入格式是微不足道的:只需让
fmt
指向不同的格式字符串即可。