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().

Declaration

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

  • *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.

Example

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)