C gets() Function Tutorial

In this section, we will learn what the gets() function is and how to use it in C.

gets() Function in C

The `gets` function is used to read a line from an incoming input stream and store it into a string-array.

gets() Function Syntax

char *gets(char *str)

gets() Function Parameters

The function takes one argument and that is a pointer to the array that the incoming string is about to be stored in it.

gets() Function Return Value

The return value of this function is the same pointer that we passed as its argument in a successful operation. But if the operation failed, the value of NULL will return instead.

Notes:

  • Unlike the `scanf` function, the `gets` function is a line reader. Which means it can read whitespaces as well.
  • This function reads the entire line of an input stream and stores it in the array, but it drops the newline character.
  • This function doesn’t check the size of the array and so we should be careful because there’s a chance that the function might overflow the array it got as its argument.

Example: C read from stdin

#include <stdio.h>
int main() {

    char array[30];

    printf("Please enter something: \n");
    gets(array);

    printf("You've entered: %s",array);

    return 0;
}

Output:

Please enter something:

My name is John

You've entered: My name is John
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies