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;