gets() string function and puts() string function

C gets() string function and puts() string function are involved with input and output operations of strings. We can use gets() function to take input and puts() function to print output of strings. Both of these functions are declared in stdio.h header file. Here in this article we will learn more and see some example program using C gets() and puts() functions.

Program using gets() string function in C

C gets() string function allows us to enter space separated strings. It gives the user facility to enter some character followed by enter key and then it will store them in a character array. The null character is added to the array for making it a string. We can take an space separated string using gets() function. Lets see the program.

// gets() function in C
#include<stdio.h>
void main(){
  char myString[100];

  printf("Enter a string here : \n");

  gets(myString);

  printf("\nYou have entered the following string : \n%s\n",myString);
}

See the output like this.

c gets and puts function, gets function in c, puts function in c

gets() string function does not perform any array bound checking and for this it is risky to use. gets() continue reading the characters until a new line is arrives which is separated by an enter. We can avoid buffer overflow using fgets() instead of using gets() function. Lets see an example program of it.

// code here

See the program output output.

Program using puts() string function in C

puts() string function is used to print the output which is received by scanf() of gets() function. It works similar as like as printf() function. Generally we use puts() function to print the string to the console.

It returns an integer which represents the number of characters to print in the console. puts() string function returns the integer value which is equal to the number of characters present in the string plus 1. Try to understand through the following C program.

// puts() function in C
#include<stdio.h>
#include <string.h>
int main(){
  char yourName[50];
  printf("Enter your name here : ");
  gets(yourName);
  printf("\nYour name is ");
  puts(yourName);
return 0;
}

Output of this puts() function is like as follows.

Enter your name here : Competitive Programmer

Your name is Competitive Programmer