I am now with conditional statements and logical operators, and the following problem arises.
If I have the following code:
string deporte;
cout << "Indica tu deporte favorito: ";
cin.get();
getline(cin, deporte);
if (deporte == "futbol" || deporte = "baloncesto")
cout << "Te gustan los deportes de equipo" << endl;
else
cout << "Lo tuyo son los deportes individuales" << endl;
The fact is that this way it does execute correctly, but if on the contrary I delete cin.get()
, the program goes directly to else
without giving the user the option to enter the data.
What am I doing wrong?
Thanks.
The problem is not in the code you present but in the code that precedes it.
A read operation does not have to remove the line break that the user enters:
The solution to this problem is by discarding whatever is in the input buffer before calling
getline
.If you assume that the user is going to use the program correctly and you know that the previous read operation is going to leave that character hanging there, you can choose to eliminate it with
cin.get
:However, you can opt for a more generic solution that passes by eliminating the entire content of the input buffer and is using
cin.ignore
. This mechanism will allow the program to work even if the user turns into a monkey pounding the keyboard unceremoniously: