2

Okay, so this is a part of my program which is basically a recurring error message to the user until a valid input is fed. So basically the issue I'm facing is that whenever I enter a number that is invalid (such as 0, 12 or a negative number), nothing will output and the program will await another input, only then will it identify the input as an error or a valid input. This is not a problem when a symbol or alphabet is input. Is there any workaround I can use?

while (Choice1 < 1 || Choice1 > 11) 
{
    if(!(cin >> Choice1), Choice1 < 1 || Choice1 > 11)
    {   
        cin.clear();
        cin.ignore(512, '\n');
        cout << "\n\aError! Please enter a valid input!" << endl;
        cout << "Now please enter the first code: ";
        cin >> Choice1;
    }
}
Dat boi
  • 33
  • 5
  • 3
    First of all, what is `Choice1`? Secondly, please read about [the built-in comma operator](http://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator) as your `if` condition uses it (in a way that makes the first condition useless). – Some programmer dude Aug 29 '18 at 11:34
  • Choice 1 is an integer variable that the user inputs at 'cin' which increments one of 12 destinations. Also, does the comma operator have to do something with this? – Dat boi Aug 29 '18 at 11:39
  • 1
    The comma is not a logical operator - `a, b` means "evaluate `a` and ignore the result, then evaluate `b`". – molbdnilo Aug 29 '18 at 11:50

1 Answers1

1

Perhaps this is what you intended:

#include <iostream>
#include <limits>

int main()
{
    int Choice1{0};

    while (!(std::cin >> Choice1) || Choice1 < 1 || Choice1 > 11) 
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

        std::cout << "Error! Please enter a valid input!" << std::endl;
        std::cout << "Now please enter the first code: " << std::endl;
    }

    return 0;
}

You can read here and/or here about the comma operator which I didn't find to belong there as part of the conditional expression. Also, I don't think you really wanted that if en-scoping the while loop. I've made some additional small changes, leaving most of the original structure -- which still could use some work.

Geezer
  • 5,600
  • 18
  • 31
  • Okay, your code seems to work but there is a problem. The first time the program is run, even if a valid input e.g. 4 is fed, it is still ignored and input is required again. Secondly, I have to achieve the aforementioned task with just the `` header file since my assignment restricts me to do so. So, is there a workaround for this? – Dat boi Aug 29 '18 at 12:22
  • @Datboi I ran just now and entering 4 is not ignored and the program is finished execution. About using only header as you can see it is the only thing being used. – Geezer Aug 29 '18 at 12:35