lundi 27 juillet 2020

Validating Integer input using booleans

In my c++ code, I would like to validate my user input to be an int between 1,10 using a do while loop. I am able to validated for integers outside of the range. However if user inputs a float or a letter, it becomes an infinite loop. My idea is to add a condition in my while loop for if the input is not an integer to keep asking for input. the CAPITAL letters is where I am having trouble.

#include <iostream>
using namespace std;


int main(){
    cout << "Welcome, ";
    int steps;
    int count=0;
    do{
        cout << "How many? \n";
        cin >> steps;
        IF (STEPS IS NOT INTEGER==TRUE){
            COUNT=1;
        }
        if (steps <1)
        {
            cout << "not enough...\n";
        }
        if (steps > 10){
            cout << "too many steps.\n Please pick a lower number of steps.\n\n";
        } 
      } while (steps < 1|| steps >10 || COUNT==1);
    
    //doing stuff with valid input


    return 0;
}

Essentially I am trying to add another condition that just returns a boolean. and if the boolean implies that the input is not valid, then it reassigns count to make sure the do while loops continues until the input is valid.

**edit: the problem i am working on asks for a max and min steps, since all of them were having a similar problem i tried to simplify it and forgot some of the edits.

Aucun commentaire:

Enregistrer un commentaire