Monday, 18 January 2010

Remove trailing newline character from asctime output

When converting a tm structure to a string using the asctime function in c++ you are left with a cstring ending with a newline character (\n). This is often a pain if you want to insert the date into another string to use later.

By looking at the contents of the cstring you can see that the last two characters are \n and \0. Therefore we just need to change the second to last character in the string from \n to \0:

struct tm * timeinfo;
char * time = asctime(timeinfo);
time(strlen(time)-1) = '\0';
cout << "The time is: " << time;
If you’re not sure what’s going on here the end of a cstring is terminated when the character \0 (A null terminator) is reached. If we look at what the cstring looks like before we use the above code it would look like this:
Sat May 20 15:21:51 2000\n\0
After the code is run it will look like this:
Sat May 20 15:21:51 2000\0\0 

2 comments:

  1. I have been tryin to write a series of output files with time in their file name so they don get over writted. I was groping with this new line problem and your info here has been god sent!!

    Thanks a lot!

    ReplyDelete
  2. time_t t = time(NULL);
    struct tm *timeinfo = localtime(&t);

    printf("The time is: %s.", strtok(asctime(timeinfo), "\n"));

    ReplyDelete