J.C.Morris
J.C.Morris

Reputation: 803

How to print individual members of a struct

I need to print out the current date in the following format : Today is Wednesday - September 7, 2012. I know I will have to use the struct

 struct tm* time_info;

I can easily accomplish this using strftime(), however, I am tasked to NOT use strftime() and extract members of the struct directly using printf statements. I cannot seem to get it to properly work. Any clues? Here is my current code:

 #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;
}

Instead of

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

I need

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

Upvotes: 2

Views: 36521

Answers (3)

nos
nos

Reputation: 229088

The struct tm has at least these members

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. 

So now you can do e.g.

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

This ofcourse will print out the month and week day as numbers, I'll leave it up to you to create a simple lookup table to get the matching English word. Use an array so you can map e.g. index 0 to "Sunday" , index 1 to "Monday" and so on.

Upvotes: 6

user529758
user529758

Reputation:

You can access individual elements of a struct using the `-> dereferencing operator:

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

You can find all the required fields of struct tm here.

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

You need to pass each member of the struct tm individually:

printf("Hour: %d  Min: %d  Sec: %d\n",
    tm_info->tm_hour,
    tm_info->tm_min,
    tm_info->tm_sec
);

Upvotes: 0

Related Questions