gets()

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.

  • It is not safe to use because it does not check the array bound.
  • It is used to read strings from the user until a newline character is not encountered.

Syntax

char *gets( char *str );

Parameters

  • str: Pointer to a block of memory (array of char) where the string read is copied as a C string.

Return Value

  • The function returns a pointer to the string where input is stored.

Example of gets()

Suppose we have a character array of 15 characters and the input is greater than 15 characters, gets() will read all these characters and store them into a variable. Since, gets() does not check the maximum limit of input characters, at any time compiler may return buffer overflow error. 

C++




// C program to illustrate
// gets()
#include <stdio.h>
#define MAX 15
 
int main()
{
    // defining buffer
    char buf[MAX];
 
    printf("Enter a string: ");
 
    // using gets to take string from stdin
    gets(buf);
    printf("string is: %s\n", buf);
 
    return 0;
}


Since gets() reads input from the user, we need to provide input during runtime.

Input:
Hello and welcome to w3wiki

Output:
Hello and welcome to w3wiki

fgets() and gets() in C language

For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets().

Similar Reads

fgets()

The fgets() reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first....

gets()

...

Conclusion

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