C gets() and puts() functions

The gets() function reads string from user and puts() function prints the string. Both functions are defined in <stdio.h> header file.

Let's see a simple program to read and write string using gets() and puts() functions.




#include<stdio.h>  
#include <string.h>
int main(){    
char name[50];    
    printf("Enter your name: ");    
    gets(name); //reads string from user    
    printf("Your name is: ");    
    puts(name);  //displays string    
 return 0;    
}    



Output:

Enter your name: Ramakrishna

Your name is: Ramakrishna

We can read a string using the %s conversion specification in the scanf function. However, it has a limitation that the strings entered cannot contain spaces and tabs. To overcome this problem, the C standard library provides the gets function. It allows us to read a line of characters (including spaces and tabs) until the newline character is entered, i. e., the Enter key is pressed. A call to this function takes the following form

gets(s);

where s is an array of char, i. e., a character string. The function reads characters entered from the keyboard until newline is entered and stores them in the argument string s, The newline character is read and converted to a null character (\O) before it is stored in s. The value returned by this function, which is a pointer to the argument string s, can be ignored. The C standard library provides another function named puts to print a string on the display. A typical call to this function takes the following form:

puts(s);

where s is an array of char, i. e., a character string. This string is printed on the display followed by a newline character.

String I/O using the gets and puts function

Consider the code segment given below.

char str[81];

puts("Enter a line of text:\n");

gets (str);

puts("You entered:\n")

puts(str);

A line of text typically contains 80 characters. Thus, the array str has been declared to store 81 characters with a provision to store the null terminator. The output of this code segment is shown below.

Enter a line of text

Programming in C language is fun'

You entered:

Programming in C language is fun!




Instagram