Page 268 - DCAP404 _Object Oriented Programming
P. 268
Unit 12: Console I/O
cin.get(c); Notes
Try using both of them and compare the results. The get(void) version is used as follows:
char c;
c = cin.get(); //cin.get(c) replaced
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. We can also use a number as an argument to the
function put (). For example,
cout << put(68); .
displays the character D. This statement will convert the int value 90 to a char value and display
the character whose ASCII value is 68.
The following segment of a program reads a line of text from the keyboard and displays it on the
screen.
char c;
cin.get (c); //read a character
while(c!= ‘\n’)
{
cout << put(c); //display the character on screen cin.get (c );
}
The getline () and write () Functions
We can read and display a line of text more efficiently using the line-oriented input/output
functions getline() and write(). The getline() function reads a whole line of text that ends with a
newline character. This function can be invoked by using the object cin as follows:
cin.getline(line, size);
This function call invokes the function which reads character input into the variable line. The
reading is terminated as soon as either the newline character ‘\n’ is encountered or size number
of characters are read (whichever occurs first). The newline character is read but not saved.
Instead, it is replaced by the null character. For example; consider the following code:
char name[20];
cin.getline(name, 20); .
Assume that we have given the following input through the keyboard:
Neeraj good
LOVELY PROFESSIONAL UNIVERSITY 261