Trap 2 - cin.get()

◀ Trap 1 - Type Cast▶ Trap 3 - Another Type Cast
Amazon This exercise evaluates your knowledge of input stream operations in C++. The following program is supposed to receive two characters from user but contains a subtle bug. Point it out and correct it.
#include<iostream>
using namespace std;

int main(int argc, char* argv[]) {
	int i;
	char c,c2;
	cout<<"Please enter your favorite character: ";
	cin.get(c);
	cout<<"Please enter your second favorite character: ";
	cin.get(c2);
cout<<"The first character you entered is "<<c; cout<<", and the second one is "<<c2<<endl; }

Solution
The bug results from incorrect use of get(). First of all, we need to be totally certain about what get() does. It reads a character the user types, including a newline. However, it does not respond until user hits enter. This is the problem. When user types, for example, “a”, then hits enter, the second get() will get that newline.

Therefore, to fix the problem, add another get() right after the first get(). You can also concatenate get() as in “cin.get(c).get();”.


This situation also exemplifies lack of understanding of the programming language. Someone who just learns get() is likely to think that a newline is not covered by get(), but he is wrong.
Let’s look at another type cast trap!
◀ Trap 1 - Type Cast▶ Trap 3 - Another Type Cast

fShare
Questions? Let me know!