2

我需要按以下格式打印当前日期:今天是星期三 - 2012 年 9 月 7 日。我知道我将不得不使用该结构

 struct tm* time_info;

我可以使用 strftime() 轻松完成此操作,但是,我的任务是不使用 strftime() 并使用 printf 语句直接提取结构的成员。我似乎无法让它正常工作。有什么线索吗?这是我当前的代码:

 #include <stdio.h>
 #include <sys/types.h>
 #include <time.h>
 #include <stdlib.h>

 /* localtime example */
 #include <stdio.h>
 #include <time.h>

 int main (void)
 {
 time_t t; 
 char buffer[40]; 
 struct tm* tm_info; 

 time(&t); 
 tm_info = localtime(&t);
 strftime(buffer, 40, " Today is %A - %B %e, %Y", tm_info); 
 puts(buffer); 


  return 0;
}

代替

 strftime(buffer, 40, " Today is %A - %B %e, %Y", tm_info); 

我需要

 printf("Today is %s, struct members info in the correct format);
4

3 回答 3

6

struct tm 至少有这些成员

int tm_sec 秒 [0,60]。
int tm_min 分钟 [0,59]。
int tm_hour 小时 [0,23]。
int tm_mday 日期 [1,31]。
int tm_mon 一年中的月份 [0,11]。
int tm_year 自 1900 年以来的年份。
int tm_wday 星期[0,6](星期日=0)。
int tm_yday 一年中的某一天 [0,365]。
int tm_isdst 夏令时标志。

所以现在你可以做例如

printf("Today is %d - %d %d, %d", tm_info->tm_wday, 
                                  tm_info->tm_mon,
                                  tm->tm_mday,
                                  1900 + tm_info->tm_year);

这当然会将月份和星期几打印为数字,我将由您来创建一个简单的查找表来获取匹配的英文单词。使用数组,以便您可以将例如索引 0 映射到 "Sunday" ,将索引 1 映射到 "Monday" 等等。

于 2012-09-05T18:26:54.333 回答
2

您可以使用 `-> 取消引用运算符访问结构的各个元素:

printf("Time is %02d:%02d:%02d\n", tm_info->tm_hour, tm_info->min, tm_info->tm_sec);

struct tm 您可以在此处找到所有必填字段。

于 2012-09-05T18:24:12.643 回答
0

您需要单独传递每个成员struct tm

printf("Hour: %d  Min: %d  Sec: %d\n",
    tm_info->tm_hour,
    tm_info->tm_min,
    tm_info->tm_sec
);
于 2012-09-05T18:22:30.357 回答