fgets() reads a line from the specified stream and stores it into the string pointed by str. It stops when either (n – 1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
However, fgets() also reads the trailing newline character and ends up returning the data string followed by ‘n’. So, in this article, we are going to see some methods to remove trailing newline characters from fgets() input.
Methods to remove trailing newline characters from fgets() input
Method 1(Using strcspn() function):
It’s a C library function that calculates the length of the number of characters before the 1st occurrence of a character present in both the strings.
Syntax:
str [ strcspn (str, “n”)] = 0;
Parameters:
str : The string in which data has been stored using fgets() i.e.(char *fgets(char *str, int n, FILE *stream))
“n”: The character till which the length should be calculated
Because we have given “n” as a second-string so we will get the length of the string before the “n”. Now put the ‘