cin.peek() and cin.putback()

◀ Short-Circuit Evaluation▶ C++ Escape Sequence Codes
Amazon While 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:
#include<iostream>
using namespace std;

int main(){
	char c;
	while((c=cin.peek()) != '!')
		cin.get(c);
	cout << "You entered '!'. The next character is ";
	cin.get(c);
cout << c << endl; return 0; }
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:
#include<iostream>
using namespace std; int main(){ char c; cin.get(c); cin.putback('c'); cin.get(c); cout<<'\n'<<c<<" is the next input character.\n"; return 0; }
Enter any character you want. The program, before terminating, outputs:
c is the next input character
If you take out the first cin.get(c), then the program will not work.

Next let’s look at C++ escape sequence codes!
◀ Short-Circuit Evaluation▶ C++ Escape Sequence Codes

fShare
Questions? Let me know!