我有两个存储两个不同日期的结构对象。我希望确保它们的格式为(dd / mm / yyyy)| (dd-mm-yyyy),然后加以区别。
如果标准格式不是dd / mm / yyyy,则打印标准错误,但似乎不接受两种格式。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
/*
# Objective: date1.c is to write in two dates and determine the difference
in the number of days between them.
Must be date inputs must be written into console as <day>/<month>/<year> |
<day>-<month>-<year>
*/
int minimumYear = 0; // O AD
int maximumYear = 10000; // 10000 AD
// Struct for the date
typedef struct {
int dd;
int mm;
int yyyy;
} dateFormat;
混乱的主要根源...
int main() {
dateFormat getDate1;
dateFormat getDate2;
//input correct date
fprintf(stderr, "Enter date in format (day/month/year): ");
scanf("%d/%d/%d", &getDate1.dd, &getDate1.mm, &getDate1.yyyy);
fprintf(stderr, "Enter date in format (day/month/year): ");
scanf("%d/%d/%d", &getDate2.dd, &getDate2.mm, &getDate2.yyyy);
}
答案 0 :(得分:2)
您应该将输入作为字符串读入fgets()
数组中,并尝试根据两种格式用sscanf()
对其进行解析。如果两种格式都不匹配输入,请投诉:
int main() {
char buf[128];
dateFormat getDate1;
//input correct date
fprintf(stderr, "Enter date in format (day/month/year): ");
if (!fgets(buf, sizeof buf, stdin)) {
fprintf(stderr, "premature end of file\n");
return 1;
}
if (sscanf(buf, "%d/%d/%d", &getDate1.dd, &getDate1.mm, &getDate1.yyyy) != 3
&& sscanf(buf, "%d-%d-%d", &getDate1.dd, &getDate1.mm, &getDate1.yyyy) != 3) {
fprintf(stderr, "invalid date: %s", buf);
return 1;
}
...
}