[Techtalk] getting the time as a string in c

Almut Behrens almut-behrens at gmx.net
Thu Sep 29 09:07:56 EST 2005


On Wed, Sep 28, 2005 at 03:25:46PM -0700, kristina clair wrote:
> Thanks for all the replies!  It was all very helpful.
> 
> I did consider using ctime(), but the problem is that I do not want a
> newline in the time string.
> 
> I thought that maybe I could replace it with a space, using something like this:
> 
>     time_t timeseconds;
>     timeseconds = time(NULL);
>     char timestring[] = ctime(&timeseconds);  /* line 13 */
>     timestring[strlen(timestring)-1] = " ";
> 
> But gcc complains:
> program.c:13: error: invalid initializer

you're close... What you want is 

     char *timestring = ctime(&timeseconds);
     timestring[strlen(timestring)-1] = '\0';

(strings in C always end at the first occurrence of a zero char ('\0'),
so whereever you put one, that's the end of the string...)

Almut


More information about the Techtalk mailing list