put() and get() functions

The classes istream and ostream define two member functions get(),put() respectively to handle the single character input/output operations.

 

There are two types of get() functions.Both get(char *) and get(void) prototype can be used to fetch a character
including the blank space,tab and newline character. The get(char *) version assigns the input character to its argument and the get(void) version returns the input character.  Since these functions are members of input/output Stream classes,these must be invoked using appropriate objects.

 

Example
 Char c;
cin.get( c ) //get a character from the keyboard and assigns it to c
while( c!=’\n’)
{ cout<< c; //display the character on screen
cin.get( c ) //get another character
}

 

this code reads and display a line of text. The operator >> can be used to read a character but it will skip the white spaces and newline character.The above while loop will not work properly if the statement
cin >> c;  is used in place of cin.get ( c );

 

The get(void) version is used as follows

…………..
char c;
c= cin.get();
…………

 

The value returned by the function get() is assigned to the variable c. The function put(), a member of ostream class can be used to output a line of text, character by character.

 

For example
cout.put(‘x’);
displays the character x and

cout.put(ch);
displays the value of variable ch.

 

The variable ch must contain a character value.A number can be used as an argument to function put().

 

For example,
cout.put(68);

displays the character D.This statement will convert the numeric value 68 to a char value and displays character whose ASCII value is 68.
The following segment of a program reads a line of text from keyboard and displays it on the screen

char c;
cin.get ( c );
while( c!= ‘\n’)
{ cout.put(c);
cin.get ( c);
}
The program below  illustrate the use of two character handling functions.

 

Program

 

Character I/O with get() and put()
 #include <iostream.h>
using namespace std;
int main()
{
 int count=0;
 char c;
 cout<<”INPUT TEXT \n”;
 cin.get( c );
 while ( c 1=’\n’ )
 { cout.put( c);
 count++;
 cin.get( c );
 }
 cout<< “\n Number of characters =” ----”\n”;
 return 0;
} 
Input
 Object oriented programming
Output
 Object oriented programming
Number of characters=27

 

Try Now – PROGRAMMING IN C++ MCQs