-4

Hello this is my second question for the same c++ program (sorry if this is a simple issue)

I am trying to use a loop to check if a input was valid. However this loop doesn't seem to respect if the input was valid or not.

int b(-1);
check = false;
while (b < 1 || b > 12)
{
    if (check)
        std::cout<<"Sorry try again!\nMonth: ";
    std::cin>>b;
    check = true;
{

If the user inputs a value between 1 and 12. Otherwise continue with the loop.

However when I run the program and input a non-valid input it continues on.

Year: 2017
Month *In number format*: 20
Day:

Even -1 doesn't work and that is weird because I set the value as -1 before the loop starts.

Year: 2017
Month *In number format*: -1
Day:

Is it the use of the or statement with less than and greater than?

bolov
  • 72,283
  • 15
  • 145
  • 224
amgtree
  • 3
  • 4

1 Answers1

1

If you enter invalid input, stream's fail bit will be set. In this case, target variable (b) is not modified and as long as you do not clear the bit, each subsequent call of operator>> will fail, too, no matter what input you provide. Actually, the input is not taken from the stream at all, so you would re-read it again and again.

You should check the state of std::in, if need be clear the error bits and discard the invalid input:

if(std::in.fail())
{
    std::in.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Aconcagua
  • 24,880
  • 4
  • 34
  • 59