What is gets_s() in C?

**gets_s()** is a built-in function defined in the <stdio.h> header. The function is available from the C11 version of C.

The following is the function prototype:

char* gets_s(char* str, rsize_t n)

Functionality

gets_s() reads data from the Standard Input, stdin, and stores it into the character array pointed to by str in the function prototype.

stdin is an input stream where data is sent to and read by a program.

The function returns str when one of the following cases occur:

  1. A newline (\n) character is read

  2. Exactly n - 1 characters have been read

The function writes the terminating null character into str before returning the character array.

What to avoid?

gets_s() returns a null pointer on failure. This may occur in any of the following cases:

  1. str is null

  2. end-of-file before storing n - 1 characters

Code

#include<stdio.h>

int main()
{
  char name[16]; //15 chars + 1 '\0' char
  
  printf("Enter Name: ");
  gets_s(name, 15);
  
  printf("Hello, %s !", name);

  return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved