如何打印结构的各个成员

J.C*_*ris 2 c time printf struct

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

 struct tm* time_info;
Run Code Online (Sandbox Code Playgroud)

我可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

代替

 strftime(buffer, 40, " Today is %A - %B %e, %Y", tm_info); 
Run Code Online (Sandbox Code Playgroud)

我需要

 printf("Today is %s, struct members info in the correct format);
Run Code Online (Sandbox Code Playgroud)

nos*_*nos 6

struct tm至少包含这些成员

int    tm_sec   Seconds [0,60]. 
int    tm_min   Minutes [0,59]. 
int    tm_hour  Hour [0,23]. 
int    tm_mday  Day of month [1,31]. 
int    tm_mon   Month of year [0,11]. 
int    tm_year  Years since 1900. 
int    tm_wday  Day of week [0,6] (Sunday =0). 
int    tm_yday  Day of year [0,365]. 
int    tm_isdst Daylight Savings flag. 

所以现在你可以这样做

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

这个当然会将月份和周日打印出来作为数字,我会留给你创建一个简单的查找表来获得匹配的英文单词.使用数组,以便您可以将索引0映射到"星期日",将索引1映射到"星期一",依此类推.