[SOLVED] I’m trying to check my array list input if its an int or string but this seems to crash and just go into infinite loop

Issue

This Content is from Stack Overflow. Question asked by Levi

void insert(){
        for(int j = 0 ; j < 10 ; j++){
            cout << "nElement you want to insert: (" << i+1 << "). ";
            if(cin >> A[j]){
                i++;
            }
            else{
                cout << "nWrong Input" << endl;
                break;
            }

Now my cin is checking if the entered number is right or wrong but its not working properly.



Solution

Here’s one way to write your insert function

void insert()
{
    int v;
    for(int j = 0 ; j < 10 ; j++)
    {
        cout << "\nElement you want to insert: (" << i+1 << "). ";
        if (cin >> v)
        {
            if (i < 10)
            {
                A[i] = v;
                i++;
            }
        }
        else
        {
            cin.clear(); // clear error
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard any pending input
        }
    }
    if (i >= 10)
        cout << "\nYour List Capacity is Full.\n" << endl;
}

The important part is the recovery from bad input. First cin.clear() is called to clear the stream error state, secondly cin.ignore(...) is called to discard any pending input.

More details here


This Question was asked in StackOverflow by Levi and Answered by john It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?