【发布时间】:2020-07-23 06:09:44
【问题描述】:
现在是 2020 年 4 月 10 日。我在 C 中制作了这个整数月份到字符串月份的转换器函数。它接受一个整数并返回一个字符串。由于某种原因,它认为是三月。我调查了问题是我的转换器还是其他问题,我打印了myTime->tm_mon,它返回2(3 月),而它应该返回3(4 月)。任何人都可以找到(我假设是)我的错误并向我指出吗?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct tm tm;
void *numberToLetters(int month) {
char *smonth;
switch (month) {
case (0):
smonth = "January";
break;
case (1):
smonth = "February";
break;
case (2):
smonth = "March";
break;
case (3):
smonth = "April";
break;
case (4):
smonth = "May";
break;
case (5):
smonth = "June";
break;
case (6):
smonth = "July";
break;
case (7):
smonth = "August";
break;
case (8):
smonth = "September";
break;
case (9):
smonth = "October";
break;
case (10):
smonth = "November";
break;
case (11):
smonth = "December";
break;
default:
return NULL;
}
return smonth;
}
int main() {
time_t present;
time(&present);
tm *myTime = &present;
void *month = (char *)numberToLetters(myTime->tm_mon);
printf("%s\n", month);
return 0;
}
【问题讨论】:
-
等等,你不能只将
time_t转换为struct tm。我认为您需要使用localtime()或gmtime()。 -
@HellmarBecker 你是对的,我的错。将更新代码
-
char * numberToLetters(unsigned month){ char *map[] = { "january" ,"february" ,"march" ,"April" ,"May" ,"June" ,"July" ,"August" ,"September" ,"October" ,"November" ,"December" }; return month < 12 ? map[month] : NULL; } -
显示的代码有太多
void*s。