Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is gets_s() in C?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

**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;
}

RELATED TAGS

c

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring