Doubt with cin.get ()

1

I am now with the conditional statements and the 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 case is that yes it is executed correctly, but if on the contrary I eliminate cin.get() , the program goes directly to else without giving the user the option to enter the data.

What am I doing wrong?

Thank you.

    
asked by Jogofus 23.11.2016 в 03:24
source

1 answer

2

The problem is not in the code that you present, but in the code that precedes it.

A read operation does not have to eliminate the line break that the user enters:

std::string var;
std::cout << "Escribe una palabra: ";
std::cin >> var; // no se elimina el salto de línea
std::cout << var << '\n';
std::cout << "Ahora escribe una frase: ";
std::getline(std::cin,var); // Se lee una cadena vacía

The solution to this problem is solved by discarding what 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 reading operation is going to leave that character hanging there, you can choose to delete it with cin.get :

std::string var;
std::cout << "Escribe una palabra: ";
std::cin >> var; // no se elimina el salto de línea
std::cout << var << '\n';
cin.get(); // Se descarta el salto de línea
std::cout << "Ahora escribe una frase: ";
std::getline(std::cin,var); // Se lee la frase esperada

However, you can choose a more generic solution that involves removing all the contents of the input buffer and using cin.ignore . This mechanism will allow the program to work even if the user turns into a monkey that beats the keyboard without consideration:

string var;
std::cout << "Escribe una frase: ";
std::cin >> var; // no se elimina el salto de línea
std::cout << var << '\n';
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // Se elimina el contenido del buffer de entrada
std::cout << "Escribe otra frase: ";
std::getline(std::cin,var); // Se lee la frase esperada
std::cout << var;
    
answered by 23.11.2016 / 09:25
source