C++ Put() and get() functions
in the c++ language the classes istream and ostream define two member functions get() and put() respectively to handle the single character input/output operations. There are two types of get functions.
We can use both get(void) and get(char*) prototypes to fetch a character including the blank space, newline and the tab character. The get(char*) version assigns the input character to its argument and second one the get(void) version returns the input character.
Since these all functions are members of the input/output stream classes, we must invoke them using an
appropriate object for example .
Example:
c;
cin.get(c) ;
(c != ‘\n’)
{
cout << c;
cin.get(c);
}
|
This code reads and displays a line of text (terminated by a newline character). Remember, the operator >> can also be used to read a character but it will skip the white spaces and newline character.
in the above example the while loop will not work properly if the statement
cin >> c;
is used in place of
cin.get(c);
|
Note: Try using both of them and compare the results.
The get(void) version will use as follows:
. . . . .
c;
c = cin.get();
. . . . .
. . . . .
The value returned by the function get() is assigned to the variable c.
The put() function is a member of the ostream class, and used to output a line of text, character by character. For example,
cout.put(‘x’);
in the above statement displays the character x and
cout.put(ch);
Here displays the value of variable ch.
|
The variable ch must contain a character value. We can also use a number as an argument to the function put(). For example,
displays the character D. This statement will convert the int value 68 to a char value and display the character whose ASCII value is 68.
The following segment of a program reads a line of the text from keyboard and also displays it on the screen.
c;
cin.get(c);
(c ! = ‘\n’)
{
cout.put(c);
cin.get(c);
}
|
in Program illustrates the use of these two character handling functions.
CHARACTER I/O WITH get() AND put()
<iostream>
using namespace std;
main()
{
count = 0;
c;
cout << "INPUT TEXT\n";
cin.get(c);
(c != '\n')
{
cout.put(c);
count++;
cin.get(c);
}
cout << "\nNumber of characters = " << count << "\n";
0;
}
|
PROGRAM OUTPUT
Input
Object Oriented Programming
output
Object Oriented Programming
Number of characters = 27
|
Note! When we type a line of input, the text is sent to the program as soon as we press the RETURN key. The program them reads one character at a time using the statement cin.get(c); and displays it using the statement cout.put(c);. The process is terminated when the newline character is encountered.