C Programming Gets() Function Tutorial with Examples – POFTUT

C Programming Gets() Function Tutorial with Examples

C and C++ programming language provide the functiongets() in order to read input from standard input which is generally a terminal. gets is the short form of the get string where string shortens as s . In this tutorial, we will learn functiongets() usage with different examples and compare with functionscanf().


The functiongets() has the following syntax which only accepts string parameter.

char *gets(char *str)
  • *str is a pointer to a string variable where string read from standard input will be put.

Return Value

The return value of the functiongets() is also the string read from standard input. If there is an error willNULL be returned which means no character read.


In this example, we will get the name from standard input and put into char array or string str then print with printf() function.

#include <stdio.h> 

int main () { 
  char str[50]; 

  printf("Enter a your name : "); 

  printf("Hello  %s", str); 


gets() vs scanf()

In this part, we will compare and find similarities and differences between gets() and scanf()

  • scanf() is a standard C function but gets is not any more
  • scanf() end taking input upon encountering whitespace, newline or EOF but gets end taking input upon encountering newline and EOF

Using Secure fgets() Function

gets() function is open to a buffer overflow which is a security vulnerability. So functionfgets() provides more secure way to read from standard input.

LEARN MORE  How To Read Input with fscanf() function In C Programming Language?

Leave a Comment