C Programming Gets() Function Tutorial with Examples

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/c-programming-gets-function-tutorial-with-examples/
PINTEREST
PINTEREST
INSTAGRAM

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

Declaration

The gets() function have 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 gets() function is also the string read from standard input. If there is an error NULL will be returned which means no character read.

Example1

In this example we will get the name from standard input and put into char array or string str and 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 anymore
  • 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 buffer overflow which is a security vulnerability. So fgets() function provides more secure way to read from standard input.

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/c-programming-gets-function-tutorial-with-examples/
PINTEREST
PINTEREST
INSTAGRAM
LEARN MORE  C - File Operations, Open, Write and Close Files