A question about how to read the strings in c ++

1

At the moment I was making a double linked list and when I started to try it I had a problem when reading the strings , I could not do that in the temp->nombre section I could read the line break, example if I wanted to put a name like "Juan Manuel" the program only read the first and ignored the other text entries. I understand that you need to use getline() for this but how? I've already tried it and it's the same

They could help me solve this.

cout<<" Dame tu nombre "<<endl;
 cin>>temp->nombre;
cin.ignore();

 cout<<" Dame tu apellido "<<endl;
 cin>>temp->apellido;
 cin.ignore();
 cout<<" Dame tu ID"<<endl;
 cin>>temp->id;
 cout<<" Dame tu Ruta"<<endl;
 cin>>temp->ruta;
 temp->num++;
 lista->anterior=temp;
    temp->siguiente=lista;
lista=temp;


}
cout<<"\t \t Conductor numero ["<<temp->num<<"]"<<endl;
cout<<"\t \t El nombre es : -> "<<lista->nombre<<endl;
cout<<"\t \t El Apellido es : -> "<<lista->apellido<<endl;
cout<<"\t \t El Id es  -> "<<lista->id<<endl;
cout<<"\t \t La ruta es : -> "<<lista->ruta<<endl;
return lista;

Here is the complete code, in case it helps.

link

    
asked by Marco Leslie 21.08.2017 в 23:53
source

2 answers

2
  

I understand that you need to use getline() for this but how? I've already tried and it's the same.

Let's see. If you have this code:

cout<<" Dame tu nombre "<<endl;
cin>>temp->nombre;
cin.ignore();

What happens is that the program will store only the first word in name ... If you want the whole line to be stored then you know that you have to use getline() . The first approach could look like this:

cout<<" Dame tu nombre "<<endl;
getline(cin,temp->nombre);
cin.ignore();

But it turns out that sometimes the program does not work because nothing is read. What is happening?

It happens that the common readings ( cin >> variable ) do not usually eliminate the line break that follows the variable to be read and, consequently, the function getline reads an empty string (the first character found is the line break and there you understand that you should stop reading).

The solution is to clean the buffer before calling getline() :

cout<<" Dame tu nombre "<<endl;
cin.ignore();
getline(cin,temp->nombre);
    
answered by 22.08.2017 / 11:20
source
2

What you should do is get the information as follows:

string variable;
getline(cin, variable);

This way you can get the whole line.

    
answered by 21.08.2017 в 23:58