If you like my posts please leave a comment.

Wednesday, August 8, 2012

Library Functions: gets( ) and puts() Functions


String I/O Functions:

In this category of library functions, we will discuss about two special functions: gets() and puts(). These functions are defined in “stdio.h”, facilitates input/output of strings (line of characters).

gets():

The gets() function provides a simple alternative to use of cin. gets() function reads a string from standard input (stdin). gets() reads the entire string including blanks. While input the string, it automatically converts the new line character (‘\n’) into the null (‘\0’) character. In contrary cin reads a string while considering a blank space present in the string as an end of the string. Let’s see the examples given below to understand this fact. 

Example 1:
//Program demonstrating the difference between gets and cin
#include<iostream.h>
#include<stdio.h>
int main()
{
char str1[80],str2[80];
cout<<"\n Enter a string using gets(): ";
gets(str1);
cout<<"\n Enter a string using cin object: ";
cin>>str2;
cout<<"\n String input with gets(): ";
cout<<str1;
cout<<"\n String input with cin object: ";
cout<<str2;
return 0;
}
Output:
 
As you can see in the above output, the gets() function has accepted the entire string including the white spaces. Whereas cin object has ignored all the characters after it has encountered the first white space.

puts():

The puts() function provides a simple alternative to use of cout. It prints the entire line of characters (String) to the standard output (stdout) and appends a new line character. In other words, put() function  is used to copy a null-terminated string to the standard output file (stdout), except the terminated NULL character. In place of NULL character, it appends the string with a new-line (‘\n’) character, while writing to the standard output file. Let’s see the example given below to understand this difference.

Example 2:
//Program to demonstrate the difference between puts and cout object
#include<iostream.h>
#include<stdio.h>
int main()
{
char str1[80],str2[80];
cout<<"\n Enter your first string: ";
gets(str1);
cout<<"\n Enter your second string: ";
gets(str2);
cout<<"\n Printing both the string using cout object\n\n";
cout<<str1;cout<<str2;
cout<<"\n\n Print both the string suing puts function\n\n";
puts(str1);puts(str2);
return 0;
}
Output:
 
Here from the above output it is clear that puts() prints the line “THIS IS THE FIRST STRING”, makes a carriage return and then prints “THIS IS THE SECOND STRING”. Whereas cout object prints both the lines without making a carriage return. 


2 comments: