0

Hi i'm attempting to validate a user input looking for an input of either 1 or 0. The string validating part seems to work fine but any integer based input has the console window accepting the input but not jumping over the if statement, returning the input (maxItems). Here is the code :

int RollingStats::GetOption() 
{
       int maxItems;

        std::cout << "Please enter either to store data individually (0) or as a range(1)" << std::endl;

        std::cin >> maxItems;

        if ((!(std::cin >> maxItems) && maxItems != 0) | (!(std::cin >> maxItems) && maxItems != 1))
        {
            std::cin.clear();

            std::cin.ignore(100, '\n');

            std::cout << "Please enter an input of either 0 or 1" << std::endl;

            GetOption();
        }
            return maxItems;
} 

Any help would be appreciated.

2
  • 3
    You should use logical OR (||) instead of bit-wise or (|) in your if condition check. Commented Dec 13, 2018 at 6:21
  • I see a d6 and I want to paint it black. -The Rolling Stats. Commented Dec 13, 2018 at 6:30

1 Answer 1

1

Some issues in the code:

  • Using cin thrice (once before if and twice in the if condition) would require the user to input thrice
  • Using logical OR (||) instead of bit-wise or (|) in your if condition check.
  • Not checking if the input is an integer

You can do something like this instead:

int RollingStats::GetOption()
{
    int maxItems;
    std::cout << "Please enter either to store data individually (0) or as a range(1)" << std::endl;
    std::cin >> maxItems;

    if(!std::cin.good() || maxItems != 0 && maxItems != 1)
    {
        std::cin.clear();
        std::cin.ignore(100, '\n');
        std::cout << "Please enter an input of either 0 or 1" << std::endl;
        maxItems = GetOption();
    } 
    return maxItems;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.