Infinite loop when I enter a character instead of an integer in C ++

2

I have a problem with a phone book that I am creating. When I ask for the number, if I enter a character, the loop repeats infinitely without giving me the possibility of re-entering the number whatever I do. I have those two blocks of code, the code that allows me to add a contact and the one that checks how many digits the number has to have. I can not understand why it stays with an infinite loop and I have tested with checks whether the std :: cin has failed and so on. Any viable solution?

void AgendaTelefonica::addContacto()
{
Contacto auxiliar;
string nombreAux;
int numAux;

cout<<"Ahora va a agregar un contacto. Introduzca su nombre: ";
cin>>nombreAux;

cout<<"\nIntroduzca su numero de telefono: ";
cin>>numAux;

while((int)contarDigitos(numAux)!=9 || !std::cin)
{
    cin.ignore();
    cin.clear();
    cout<<"Por favor,introduzca un numero de 9 digitos: ";
    cin>>numAux;
}

auxiliar.nombre = nombreAux;
auxiliar.numeroTfn = numAux;

int j = 1;

for(int i=0;i<j;i++)
{
    if(contactos[i].nombre == "")
    {
        auxiliar.posicion = i;
    }
    else{j++;}
}

cout<<"\nLa posicion del contacto es "<<auxiliar.posicion<<endl;

contactos[auxiliar.posicion] = auxiliar;

numContactos++;
}



int AgendaTelefonica::contarDigitos(int numero)
{
int n = numero;
int count = 0;

while (n != 0)
{
    n /= 10;
    count++;
}

return count;
}
    
asked by AbsydeAuberon 02.07.2018 в 12:37
source

1 answer

1

I have the answer to your question

The problem is that when you enter the character in cin when waiting for a number, that character ignores it, finds a line break and stops, as the loop repeats when you do not enter the number, the cout is printed again and the cin is launched again, as the line break continues to exist, an infinite loop will be created. cin has a method, fail that detects good if data entry is wrong

void clear_cin() {
 std::cin.clear(); // limpiamos el estado de cin para que quede como good()
 std::cin.ignore(80, '\n'); // ignoramos todos los carácteres (máximo 80) hasta fin de línea.
}

if (std::cin.fail()) { // Si no nos ha introducido un número, cin queda en el estado "fail"
    clear_cin(); // limpiamos cin para que vuelva a un estado correcto
    std::cout << "debe ser un número" << std::endl;
}

Any doubt you tell me

    
answered by 02.07.2018 / 15:04
source