简体   繁体   中英

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.

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.

You can check whether the input failed, ie the user entered something that could not be read as an int like this:

if (cin.fail()) {  // in place of IF (STEPS IS NOT INTEGER==TRUE)
  cin.clear();      
  cin.ignore();
  cout << "not an integer, try again\n";
  continue;
}

This avoids the need for the COUNT variable.

Also, your while condition doesn't appear to match the checks inside the loop. What happens when step is either 9 or 10 ? You should be consistent with the checks inside the loop.

You could use the ! operator.

For example:

if ( !(std::cin >> steps) )
        {
          std::cin.clear();
          std::cin.ignore();
          std::cout << "Incorrect entry. Try again: ";
        }

Also consider not using using namespace std; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM