我目前正在开发一个c项目,我正在尝试从系统中获取日期并将其构建为字符串。
我对c很新,所以我现在正在学习,但是我不能让它工作。以下是我的代码
time_t now = time(NULL);
struct tm *t = localtime(&now);
char currentDate[13];
char day[3];
char month[3];
char year[5];
char hour[3];
char min[3];
sprintf(day, "%02d", t->tm_mday, sizeof(day));
sprintf(month, "%02d", t->tm_mon+1, sizeof(month));
sprintf(year, "%04d", t->tm_year + 1900, sizeof(year));
sprintf(hour, "%02d", t->tm_hour, sizeof(hour));
sprintf(min, "%02d", t->tm_min, sizeof(min));
strcat(currentDate, day);
strcat(currentDate, month);
strcat(currentDate, year);
strcat(currentDate, hour);
strcat(currentDate, min);
printf("Current Date: %s", currentDate);
当它执行printf时,它只会打印出一堆垃圾,例如
当前日期:ÃÃx·························································································································
我做错了什么。
答案 0 :(得分:10)
我会考虑使用ctime和/或strftime。它可能会让你得到你想要的东西,而不会过多地使用字符串和时间字段。
使用strftime:
char text[100];
time_t now = time(NULL);
struct tm *t = localtime(&now);
strftime(text, sizeof(text)-1, "%d %m %Y %H:%M", t);
printf("Current Date: %s", text);
答案 1 :(得分:6)
答案 2 :(得分:2)
char currentDate[12] = {'\0'};
currentDate包含随机数据且未初始化,因此strcat会查找终止该字符串的零。
答案 3 :(得分:1)
@markWilkins的回答是正确的,但是一次性打印字符串可能更容易。
sprintf(currentDate, "%02d%02d%04d%02d%02d", t->tm_mday, t->tm_mon+1,
t->tm_year + 1900, t->tm_hour,t->tm_min);
这允许您将格式视为一个,这意味着您不必执行所有字符串操作。
另请注意,sprintf不会将最大大小作为参数