Capture data with getline

2

I have problems with this function ... it turns out that when I execute it, it is printed on the screen directly: name > date > ... , and I can not capture the name.

I have the libraries <iostream>,<fstream>,<string> y <windows.h> .If someone can explain me why this happens and how I could solve it. thanks !!

void Menus::menuCarreras(){
    int opcion;

    while (opcion != 6){
        cout<<"...SELECCIONAR OPCION..."<<endl;
        cout<<"[1] -> AGREGAR CARRERA"<<endl;
        cout<<"[2] -> BUSCAR CARRERA"<<endl;
        cout<<"[3] -> ELIMINAR CARRERA"<<endl;
        cout<<"[4] -> MODIFICAR CARRERA"<<endl;
        cout<<"[5] -> MOSTRAR CARRERAS"<<endl;
        cin>>opcion;

        if(opcion == 1) {
            string nNombre, nFecha;
            float nInscripcion;

            Carrera *nCarrera = new Carrera();

            cout<<"nombre -> ";
            getline(cin, nNombre);
            nCarrera->setNomCarrera(nNombre);

            cout<<"fecha -> ";
            getline(cin, nFecha);
            nCarrera->setFecha(nFecha);

            cout<<"Inscripcion -> ";
            cin>>nInscripcion;
            nCarrera->setInscripcion(nInscripcion);

            misCarreras->agregar(nCarrera); }

            misCarreras->mostrar();
    }
}
    
asked by Steven 24.04.2018 в 07:10
source

1 answer

2

Surely you are thinking that this instruction:

cin>>opcion;

Not only does it read an integer but it also cleans the input buffer and it does not ... in the input buffer the line break remains as residue. Successive calls to cin eliminate this line break and therefore a code such that:

int a, b;
std::cin >> a >> b;

It works independently of whether the separator used between both variables is a space (or twenty spaces) or a line break ... however with getline that does not happen. getline needs that line break to disappear and for this you can use cin.ignore() :

cin>>opcion;
cin.ignore(); // Elimina el siguiente caracter

And that's it, now your program should work.

    
answered by 24.04.2018 / 07:25
source