I use function ascitime 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"(resp. char *):
Sun Sep 16 01:03:52 1973\n\0
How can I rid of "\n" from this string? I don't want nextline which cause "\n". Thx
The other answers seem overcomplicated. Your case is simple because you know the unwanted character is the last one in the string.
char *foo = asctime();
foo[strlen(foo) - 1] = 0;
This nulls the last character (the \n).
After Accept Answer
The accepted answer seems over complicated. asctime()
returns a pointer to a fixed sized 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
The general solution to removing a potential (trailing) '\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';
// or
str[strcspn(str,"\n")] = '\0';
str[strlen(str) - 1]
is not safe until first establishing strlen(str) > 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With