Why does this code go into an infinite loop?

1

Good morning, I am learning to program in C ++. I'm writing a program to practice and I do not know why it goes into an infinite loop. I tried to clean the cin buffer but it does not work.

  while(state){
    cout<<opciones<<endl;
    cin>>opcion;
    cout<<opcion<<endl;
    switch(opcion){
        case 1:
            cout<<"funcionoo"<<endl;
            break;
        case 2:

            break;
        case 3:

            break;
        case 4:
            state=0;
            break;
        default:
            string sep2(anchodepantalla,'*');
            cout<<"Opcion no valida. Intentelo de nuevo."<<endl;
            cout<<sep2<<endl;
            break;
    }
    opcion=0;
    cin.ignore();
}
    
asked by Andres V. 15.03.2017 в 00:30
source

1 answer

1

In while std::cin is waiting for int if you do not have something right to put it in int fails:

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int state = 1;
    int opcion = 0;

    while(state){
    //cout<<opciones<<endl;

    //cin espera un int comprueba que es un entero;
    if (cin >> opcion) {

    } else {

      //buscamos el default
      opcion = 0;
    }
    //cout<<opcion<<endl;
    switch(opcion){
        case 1:
            cout<<"funcionoo"<<endl;
            break;
        case 2:

            break;
        case 3:

            break;
        case 4:
            state=0;
            break;
        default:

            cout<<"Opcion no valida. Intentelo de nuevo."<<endl;

            break;
    }

    //cin.ignore();
}
    return 0;
}

I think this works as expected, count on what part of the code I imagined.

    
answered by 15.03.2017 / 03:34
source