C - Using fgets() for text input

Introduction

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:

fgets(string,size,stdin); 
  • 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.

Demo

#include <stdio.h> 

int main() /* w w  w .ja v a2  s. c  o m*/
{ 
     char name[10]; 

     printf("Who are you? "); 
     fgets(name,10,stdin); 
     printf("Glad to meet you, %s.\n",name); 
     return(0); 
}

Result

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