C - Console Input String Input

Introduction

gets_s() function in stdio.h will read a complete line of text as a string.

The prototype of the function is as follows:

char *gets_s(char *str, rsize_t n);

This function reads up to n-1 successive characters into the memory pointed to by str until you press the Enter.

It appends the terminating null, '\0', in place of the newline character.

If an error occurs during input, str[0] will be set to the '\0' character.

Demo

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>

int main(void)
{
  char initial[3] = { ' ' };
  char name[80] = { ' ' };

  printf("Enter your first initial:  ");
  gets_s(initial, sizeof(initial));
  printf("Enter your name:  ");
  gets_s(name, sizeof(name));
  if (initial[0] != name[0])
    printf("%s, you got your initial wrong.\n", name);
  else//ww w . j  ava2 s  .c  om
    printf("Hi, %s. Your initial is correct. Well done!\n", name);
  return 0;
}

Result

You read the initial and the name as strings using gets_s().

gets_s() will read characters until n-1 characters have been read or when you press the enter key.

The newline character is not stored.

To retain the newline character, use the fgets() function.

printf("Enter your first initial:  ");
fgets(initial, sizeof(initial), stdin);
printf("Enter your name:  " );
fgets(name, sizeof(name), stdin);

Exercise