Reputation: 21
I am still new to c. I am trying to log the time and date into an array
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
int main(void) {
char prompt, start = 0;
char arr[20];
struct tm *sTm;
time_t now = time(0);
sTm = gmtime(&now);
strftime(arr, sizeof(arr), "%Y-%m-%d %H:%M:%S", sTm);
printf("%s %s\n", arr, "Event occurred now");
printf("Time is %d:%d:%d Date is %d-%d-%d \n", sTm->tm_hour, sTm->tm_min, sTm->tm_sec, sTm->tm_mday, sTm->tm_mon+1,sTm->tm_year+1900);
printf("Press and key to exit \n\r");
scanf("\n%c", &prompt);
return 0;
}
in short I want the values of this line
printf("Time is %d:%d:%d Date is %d-%d-%d \n", sTm->tm_hour, sTm->tm_min, sTm->tm_sec, sTm->tm_mday, sTm->tm_mon+1,sTm->tm_year+1900);
in an array such as Timeanddate[1] = 14:53:04,20/3/2016
Upvotes: 2
Views: 2775
Reputation: 824
Saving a single datetime string is different than saving multiple datetimes into an array of datetimes.
If you are saving one datetime then define a character buffer to hold enough characters In your string plus the NUL character. In your case with HH:MM:SS,dd/mm/yyyy you need 19-characters plus the NUL character.
char Timeanddate[20];
If you are saving an array of datetimes then you need to decide if you need an unknown number of array elements and so need to to have the array grow in size or if you can assume a limited number of array entries. If the array has to grow after you define it then that makes it difficult in C.
For multiple datetimes you will need a two dimensional character array. Assuming you know the number of entries (say 5-different date/times) then define an array of 5-strings of 20-bytes each.
char Timeanddate[5][20];
Then you have to write into the character buffer of your choice the value of the datetime. You should use snprint() rather than sprintf() as snprintf() will prevent accidentally writing too many bytes into your array element and thus overflowing your buffer and leading to bad results when you run your application.
For a single datetime string
snprintf(Timeanddate, sizeof(Timeanddate), "%d:%d:%d,%d/%d/%d", sTm->tm_hour, sTm->tm_min, sTm->tm_sec, sTm->tm_mday, sTm->tm_mon+1,sTm->tm_year+1900);
For an array of datetime strings
snprintf(Timeanddate[0], sizeof(Timeanddate[0]), "%d:%d:%d,%d/%d/%d", sTm->tm_hour, sTm->tm_min, sTm->tm_sec, sTm->tm_mday, sTm->tm_mon+1,sTm->tm_year+1900);
Upvotes: 1
Reputation: 940
You can use sprintf or snprintf instead of using printf, that will save your output into an array. But you have to do it one by one.
refer how to store printf into a variable? also for much clarification.
Upvotes: 0