c – Removing trailing newline character from fgets() input

c – Removing trailing newline character from fgets() input

Perhaps the simplest solution uses one of my favorite little-known functions, strcspn():

buffer[strcspn(buffer, n)] = 0;

If you want it to also handle r (say, if the stream is binary):

buffer[strcspn(buffer, rn)] = 0; // works for LF, CR, CRLF, LFCR, ...

The function counts the number of characters until it hits a r or a n (in other words, it finds the first r or n). If it doesnt hit anything, it stops at the (returning the length of the string).

Note that this works fine even if there is no newline, because strcspn stops at a . In that case, the entire line is simply replacing with .

The elegant way:

Name[strcspn(Name, n)] = 0;

The slightly ugly way:

char *pos;
if ((pos=strchr(Name, n)) != NULL)
    *pos = ;
else
    /* input too long for buffer, flag error */

The slightly strange way:

strtok(Name, n);

Note that the strtok function doesnt work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the n character intact.

There are others as well, of course.

c – Removing trailing newline character from fgets() input

size_t ln = strlen(name) - 1;
if (*name && name[ln] == n) 
    name[ln] = ;

Leave a Reply

Your email address will not be published.