How can I get rid of "\ n" from a string in c?
I am using the ascitime function in C
#include <time.h> char *asctime(const struct tm *timeptr); returns something like: Sun Sep 16 01:03:52 1973\n\0 It returns this "string" (respectively char *):
Sun Sep 16 01:03:52 1973 \ n \ 0
How can I get rid of "\ n" from this line? I do not need the next line that calls "\ n". thanks
Other answers seem complicated. Your case is simple because you know that the unwanted character is the last in the string.
char *foo = asctime(); foo[strlen(foo) - 1] = 0; This returns the desired character (\ n).
After accepting the answer
the accepted answer seems complicated. asctime() returns a pointer to a fixed-size array of 26 in the form:
> Sun Sep 16 01:03:52 1973\n\0 > 0123456789012345678901234455 char *timetext = asctime(some_timeptr); timetext[24] = '\0'; // being brave (and foolish) with no error checking A general solution to removing a potential (final) '\n' that is more resistant to unusual strings would be:
char *some_string = foo(); char *p = strchr(str, '\n'); // finds first, if any, \n if (p != NULL) *p = '\0'; // or size_t len = strlen(str); if (len > 0 && str[len-1] == '\n') str[--len] = '\0'; str[strlen(str) - 1] not safe until strlen(STR) > 0 is first set.
Why not use printf with maximum width? seeing what you still call printf ...
static void debug_printf(const char *format, ...) { va_list arglist; time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); printf ( "%.24s: ", asctime (timeinfo) ); va_start( arglist, format ); vprintf( format, arglist ); va_end( arglist ); } As far as I know, you cannot force it to return a string without a new string. You just need to disable \n with the base loop.
int i; for(i = 0;; i++) { if(str[i] == '\n') { str[i] = '\0'; break; } } Alternatively, you can read the information manually from tm struct .
If you want to do this with 1 line of code:
printf("The time is: %s.", strtok(asctime(timeinfo), "\n"));