gets() in C++

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The gets() function, declared in the <cstdio> header file, reads a line from stdin until a new line or end of the file is reached.

Syntax of gets() in C++

The syntax of function gets in C++ is as follows:

Parameters of gets() in C++

The function gets in C++ accepts a pointer to the array of characters where the data is to be stored.

Return value of gets() in C++

1. On Success: It returns the pointer to that string/array of characters in which the data was stored. 2. On Failure: Null Pointer.

Example

Input:

Output:

In the above code, we take input for str using gets() function.

What is gets() in C++

The gets() function in C++ reads characters from the stdin until a new line or end of the file is reached. It accepts a pointer to the memory where it stores those array of characters. After successfully writing characters in the character array, a terminating null character is automatically appended after the characters are copied to str.

This function was deprecated in C++ 11 and removed in C++ 14. Also, while using this function in previous versions, C++ shows a warning after compilation which goes like this,
Warning: the gets function is dangerous and should not be used.

This function doesn't set a limit on storing data in the buffer, which means it doesn't prevent the buffer overflow to the destination memory and keeps reading the data. In such a case, it terminates the program with a runtime error.

More Examples

Buffer Overflow Example

This is the most problematic scenario while using the function gets in C++.

Input:

Output:

In the above code, the input stream is greater than the size of the character array, due to which the program gives a runtime error.

Conclusion

  • The gets() function is declared in <cstdio> header file.
  • It reads the characters from stdin until a newline character is found or the end of the file is reached.
  • The function gets in C++ doesn't handle the case of buffer overflow.
  • Newer versions of C++ no longer support it.
  • It was deprecated in C++ 11 and removed in C++ 14.