Chapter 16.6

cin.peek() and cin.putback()

AmazonWhile not being particularly useful, cin.peek() and cin.putback() accomplish something that may come in handy some day. cin.peek() returns the next input character without taking it out of the input stream. Here is a sample program:

The program terminates when you enter ! somewhere and hit enter key. If the program terminates, it always outputs:

You entered ‘!’. The next character is !

because cin.peek() puts ! back to input stream for cin.get() to get it.

cin.putback(), as the name suggests, puts a character back to the beginning of the input stream. One thing noteworthy is that you must read a character before you use this function. Here is a sample program: