C gets() Function : C Reference



gets() function : Reading or Accepting String From User in C

Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached.


Syntax for Accepting String :

char * gets ( char * str );

OR

gets( <variable-name> )

Live Example :

#include<stdio.h>

void main()
{
char name[20];
printf("\nEnter the Name : ");
gets(name);
}

Explanation :

  1. Whenever gets() statement encounters then characters entered by user (the string with spaces) will be copied into the variable.
  2. If user start accepting characters , and if new line character appears then the newline character will not be copied into the string variable(i.e name).
  3. A terminating null character is automatically appended after the characters copied to string vriable (i.e name)
  4. gets() uses stdin (Standered Input Output) as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for string variable (which can lead to buffer overflows).

Some Legal Declarations :

Statement Use Size Terminates
gets(name) Accepting Name of Person with Spaces No Specification After Enter Key
gets(city) Accepting Name of City No Specification After Enter Key
gets(address) Accepting address with Spaces No Specification After Enter Key
gets(bname) Accepting book name No Specification After Enter Key

Some Rules and Facts : 

A. %s is not Required :

Like scanf statement %s is not necessary while accepting string.

scanf("%s",name);

and here is gets() syntax which is simpler than scanf() –

gets(name);

B. Spaces are allowed in gets() :

gets(name);

Whenever the above line encounters then interrupt will wait for user to enter some text on the screen. When user starts typing the characters then all characters will be copied to string and when user enters newline character then process of accepting string will be stopped.

Sample Input Accepted by Above Statement :

Value Accepted : Pritesh Taral\n
Value Stored   : Pritesh Taral    (\n Neglected)