Please write a C function that can read a data in three different formats.
EXAMPLE INPUT
2018年12月30日
12/3/2018
2018-12-15
Dec. 5, 2018
EXAMPLE OUTPUT
2018年12月30日
12/3/2018
2018/12/15
Wrong format
主程序 (不能修改)
#include <stdio.h>
#include <stdlib.h>
enum Format { CHINESE, MONTH_FIRST, YEAR_FIRST, WRONG };
struct Date
{
int year;
int month;
int day;
enum Format format;
};
void printDate(struct Date date) {
switch (date.format) {
case CHINESE: printf("%d年%d月%d日\n", date.year, date.month, date.day); break;
case MONTH_FIRST: printf("%d/%d/%d\n", date.month, date.day, date.year); break;
case YEAR_FIRST: printf("%d/%d/%d\n", date.year, date.month, date.day); break;
default: puts("Wrong format");
}
}
#include "source.c"
int main() {
for (int i = 0; i < 4; ++ i) {
struct Date date = readDate();
printDate(date);
}
}
我的答案
struct Date readDate(){
struct Date date;
char s[100];
fgets(s,1000,stdin);
if(sscanf(s,"%d年%d月%d日", &date.year, &date.month, &date.day)==3){
date.format=CHINESE;
}
else if(sscanf(s,"%d/%d/%d", &date.month, &date.day, &date.year)==3){
date.format=MONTH_FIRST;
}
else if(sscanf(s,"%d-%d-%d", &date.year, &date.month, &date.day)==3){
date.format=YEAR_FIRST;
}
else{
date.format=WRONG;
}
return date;
}