jeudi 22 février 2018

Strange if statement turning into infinite loop in c++

Below you can see a do while cycle for inputting strength stats, the program works fine but if in the section where you input the number (cin >> RemainingNumber) if you input a character of any kind it starts a infinite loop.

int RemainingStats;
int CurrentStats = 20;
do 
{
    //Cycle For Strength
    cout << "Please input a number between 0 and " << CurrentStats << " for strength: " << endl;
    cin >> RemainingStats;
    if (RemainingStats > CurrentStats || RemainingStats < 0)
    {
        cout << "Invalid input please input a number betwen 0 and " << CurrentStats << endl;
    }
    else if (RemainingStats < CurrentStats || RemainingStats > 0)
    {
        strength += RemainingStats;
        cout << "Strength: " << strength << endl;
    }
} while (RemainingStats > CurrentStats || RemainingStats < 0);

It starts showing you this part of the code constantly

{cout << "Please input a number between 0 and " << CurrentStats << " for strength: " << endl;
    cin >> RemainingStats;
    if (RemainingStats > CurrentStats || RemainingStats < 0)
    {
        cout << "Invalid input please input a number betwen 0 and " << CurrentStats << endl;
    }

except the fact that it does not let you cin RemainingStats and just continues to the if statement, if anyone can help and explain i will really apretiate it.

image of the result when you input the character

Aucun commentaire:

Enregistrer un commentaire