Help with cin function.getline C++
Greetings.
I have a problem with the following C++ code
#include <iostream>
#include <cstdlib>
using namespace std;
int main () {
int n;
cout << "Ingrese la cantidad de valores a procesar: ";
cin >> n;
char nombre[n][500];
for (int i = 0; i < n; i++) {
cout << "Escriba el nombre: ";
cin.getline(nombre[i], 500);
}
for (int j = 0; j < n; j++) {
cout << "\nEl valor ingresado es: " << nombre[j];
}
return 0;
}
When I give a fixed value to the string array subscript, I have no problem entering and displaying the names to the program; but when I don't specify the value and take it from the variable "n", the For loop only shows me the output "type the name" and immediately exits the loop.
Does anyone know what it's due to?
Thank you!
2 answers
Try adding this line after reading n
:
cin >> n;
cin.ignore();
This is because of the way cin >>
and cin.getline
work.
When you assign a value like this, the line change characterEnter also remains pending in the input (buffer).
The function cin.getline
reads the input until it encounters the line change character (by default), but unlike cin >>
does not leave it in the input.
So what happens in your code is that when it's your turn to run cin.getline
the first time, what you find is a line change and enter a blank name.
cin.ignore()
tell the input to discard what is pending, so there is no conflict.
int cantidadDeCadenas = 0;
cout << "Indique la cantidad de lineas de entrada" << endl;
cin >> cantidadDeCadenas;
/*->>>> here is the magic that shared * / cin.ignore ();
vector<string> datos;
for (int i = 0; i < cantidadDeCadenas; i++) {
cout << "Introdusca la linea " << i << ": " << endl;
string lineaCadena;
getline(cin, lineaCadena);
datos.push_back(lineaCadena);
}
/ / with this we read N lines greetings and many thanks for the help