Gets c function – gets C Library Function

Gets c function: The function char *gets(char *str); reads characters from the standard input stream (stdin) and stores it as a null terminated string into str until a newline character or the end-of-file is reached, whichever comes first. A null character(‘\0’) is automatically added after the characters copied to str.

Function prototype of gets

char *gets(char *str);
  • str : This is the pointer to an character array where the characters copied from stdio stream is stored.

Return value of gets

Gets in c: On Success, this function returns the str pointer after copying the character read from the stdio stream otherwise returns NULL in case of error or If end of file is reached before reading any characters.

C program using gets function

How to use gets in c: The following program shows the use of gets function to read a string from user and print it back on screen.

gets C Library Function

#include <stdio.h>
 
int main(){
   char string[50];
 
   printf("Enter your name\n");
   gets(string);
 
   printf("You name is %s", string);
    
   return(0);
}

Output

Enter your name
Jack Dawson
You name is Jack Dawson