Search code examples
cstringfgetsstrlen

fgets() doesn't retain '\n' for the input of size of array


I have gone through many posts on SO regarding the preferred use of fgets() over scanf() and gets().Some referred about the fgets() man page.

Then there is this wonderful post showing the number of characters stored by fgets() by using strlen().One of the answers on this post mentioned as described in the man page that fgets() retains the \n(if any) and that's why the strlen() function returns text_size+1. I tried to test it through a program :

#include<stdio.h>
#include<string.h>
#define text_size 10
int main(void)
{
  char str[text_size+1];
  fgets(str,sizeof(str),stdin);
  printf("%s",str);
  printf("%d",strlen(str));

     return 0;
}

when I input text of size smaller than text_size ,the strlen(str) returns the value (text_size+1) which is quite understandable to me after reading the man page that it retained the \n after text. As for example:-

INPUT: hello

OUTPUT: hello 6 (i guess \n is retained here).

But when I input text of exact size as text_size or even larger size the value returned by strlen(str) is equal to (text_size) and hence 10 is printed out,I wonder why the \n is discarded here?

INPUT: helloworldhi

OUTPUT: helloworld 10(why 11 is not returned here since 1 more character place is still there , i don't understand here which of the characters here has been given preference \0 or \n and why???

I am not pretty sure about all the undefined behavior in C, but can we call it an UB?


Solution

  • fgets(str,sizeof(str),stdin);
    

    You specify here the size of your buffer, thus when there is too much text, it will only read in (size - 1) characters, to make room for a null character.

    Take a look at fgets

    Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.