C - Using fgets() for text input


fgets() function has the format:

#include <stdio.h> 

char * fgets(char *restrict s, 
             int n, 
             FILE *restrict stream); 

You can use fgets() to read text from the keyboard.

Here's a simplified version of the fgets() function as it applies to reading text input:

  • string is the name of a char array, a string variable;
  • size is size of the char array; and
  • stdin is the name of the standard input device, as defined in the stdio.h header file.


#include <stdio.h> 

int main() //from  w w w  . j  a v a 2s .  c om
     char name[10]; 

     printf("Who are you? "); 
     printf("Glad to meet you, %s.\n",name); 


The fgets() function reads in text. The text goes into the name array, which is set to a maximum of ten characters.

The number 10 specifies that fgets() reads in only nine characters, one less than the number specified.

stdin is standard input.

The char array must have one extra character reserved for the \0 at the end of a string.

Its size must equal the size of input you need - plus one.

Related Example