-
asctime()
I'm trying to use the function asctime() and save the function output to a string, but I can't figure out how to do it. What I've posted is the only way I can get it to compile without errors, but it's obviously wrong. Am I missing something obvious?
Code:
main()
{
time_t lt;
struct tm t, *tmptr;
lt=time(NULL);
tmptr=localtime( & lt );
char strings[26];
const char *chptr=strings;
chptr=asctime(tmptr);
printf("%s\n%s",asctime(tmptr),strings);
return 0;
}
-
You mean
strcpy(strings,asctime(tmptr));
You're writing C++ with those embedded declarations you know.
-
Thanks Salem, that was a little obvious:o I guess I don't work with the standard functions enough. And no, I wasn't sure if it was C++ or not, but I have seen it in my C++ book:D
-
Code:
#include <time.h>
int main(int argc, char *argv[])
{
time_t lt;
struct tm t, *tmptr;
char tmp[26]={'\0'};
lt=time(NULL);
tmptr=localtime( & lt );
strcpy(tmp,asctime(tmptr));
printf("%s\n",asctime(tmptr));
printf("%s\n",tmp);
return 0;
}
asctime() returns a static char *, which will change with subsequent calls to time functions; this makes a local copy.