The steps to remove the newline character in the perhaps most obvious way:
NAME
by using strlen()
, header string.h
. Note that strlen()
does not count the terminating \0
.size_t sl = strlen(NAME);
\0
character (empty string). In this case sl
would be 0
since strlen()
as I said above doesn´t count the \0
and stops at the first occurrence of it: if(sl == 0)
{
// Skip the newline replacement process.
}
'\n'
. If this is the case, replace \n
with a \0
. Note that index counts start at 0
so we will need to do NAME[sl - 1]
:if(NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
Note if you only pressed Enter at the fgets()
string request (the string content was only consisted of a newline character) the string in NAME
will be an empty string thereafter.
if
-statement by using the logic operator &&
:if(sl > 0 && NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
size_t sl = strlen(NAME);
if(sl > 0 && NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
If you rather like a function for use this technique by handling fgets
output strings in general without retyping each and every time, here is fgets_newline_kill
:
void fgets_newline_kill(char a[])
{
size_t sl = strlen(a);
if(sl > 0 && a[sl - 1] == '\n')
{
a[sl - 1] = '\0';
}
}
In your provided example, it would be:
printf("Enter your Name: ");
if (fgets(Name, sizeof Name, stdin) == NULL) {
fprintf(stderr, "Error reading Name.\n");
exit(1);
}
else {
fgets_newline_kill(NAME);
}
Note that this method does not work if the input string has embedded \0
s in it. If that would be the case strlen()
would only return the amount of characters until the first \0
. But this isn´t quite a common approach, since the most string-reading functions usually stop at the first \0
and take the string until that null character.
Aside from the question on its own. Try to avoid double negations that make your code unclearer: if (!(fgets(Name, sizeof Name, stdin) != NULL) {}
. You can simply do if (fgets(Name, sizeof Name, stdin) == NULL) {}
.