sfactor sfactor - 1 year ago 144
C Question

Removing trailing newline character from fgets() input

I am trying to get some data from the user and send it to another function in gcc. The code is something like this.

printf("Enter your Name: ");
if (!(fgets(Name, sizeof Name, stdin) != NULL)) {
fprintf(stderr, "Error reading Name.\n");

However, I find that it has a newline
character in the end. So if I enter
it ends up sending
. How do I remove that
and send a proper string.

Answer Source

The slightly ugly way:

char *pos;
if ((pos=strchr(Name, '\n')) != NULL)
    *pos = '\0';

The slightly strange way:

strtok(Name, "\n");

Note that the strtok function doesn't 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download