Use struct tm to print a specific date and strftime
所以我需要专门使用struct tm打印我的生日,这是我成功完成的。但是,我还需要使用strftime()以不同的格式打印它。
那就是我遇到的问题,因为strftime()仅识别指针参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <stdio.h> #include <time.h> int main(){ struct tm str_bday; time_t time_bday; char buffer[15]; str_bday.tm_year = 1994 - 1900 ; str_bday.tm_mon = 7 - 1; str_bday.tm_mday = 30; str_bday.tm_hour = 12; str_bday.tm_min = 53; time_bday = mktime(&str_bday); if(time_bday == (time_t)-1) fprintf(stdout,"error\ "); else { fprintf(stdout,"My birthday in second is: %ld \ ",time_bday); fprintf(stdout,"My birthday is: %s\ ", ctime(&time_bday));//Wed July 22 12:53:00 1998 strftime(buffer,15,"%d/%m/%Y",time_bday); fprintf(stdout,"My birthday in D/M/Y format is %s",buffer); } return 0; } |
错误为:
1 2 3 | Error: passing argument 4 of a€?strftimea€? makes pointer from integer without a cast expected a€?const struct tm * restricta€? but argument is of type a€?time_ta€? |
有人可以告诉我如何解决吗?
编辑:将time_bday更改为
通过查看
1 |
在您的情况下为
首先初始化
1 2 | // struct tm str_bday; struct tm str_bday = { 0 }; |
OP的代码无法初始化某些成员,例如
然而,初始化所有相关成员也很重要。 OP的代码未分配
1 | str_bday.tm_isdst = 0; // Set time stamp to **standard** time. |
麻烦的是,在OP的学校中,该日期的夏令时设置肯定是夏令时。
1 2 3 4 5 6 | // add str_bday.tm_isdst = -1; // Let mktime() determine DST setting // or if one knowns it is daylight time. str_bday.tm_isdst = 1; // Set time stamp to **daylight** time. // or if one knowns it is standard time. str_bday.tm_isdst = 0; // Set time stamp to **standard** time. |
该错误应该在打印
时显而易见
1 2 | // My birthday is: Sat Jul 30 13:53:00 1994 My birthday is: Sat Jul 30 12:53:00 1994 |
更正的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <locale.h> #include <time.h> int main() { struct tm str_bday = { 0 }; time_t time_bday; char buffer[15]; str_bday.tm_year = 1994 - 1900; str_bday.tm_mon = 7 - 1; str_bday.tm_mday = 30; str_bday.tm_hour = 12; str_bday.tm_min = 53; str_bday.tm_isdst = -1; time_bday = mktime(&str_bday); strftime(buffer, sizeof buffer,"%d/%m/%Y", &str_bday); if (time_bday == (time_t) -1) { fprintf(stdout,"error\ "); } else { // Do not assume `long`. Better to cast to a wide type. fprintf(stdout,"My birthday in second is: %lld \ ", (long long) time_bday); fprintf(stdout,"My birthday is: %s", ctime(&time_bday)); // strftime(buffer,15,"%d/%m/%Y",time_bday); strftime(buffer, sizeof buffer,"%d/%m/%Y", &str_bday); fprintf(stdout,"My birthday in D/M/Y format is %s\ ", buffer); } return 0; } |
1个成员