do...while loop broken

I can't seem to get the desired output from my code below. It should except only input 1 thru 12, but it accepts anything. It should output"Please enter the month between 1 - 12." if the number is above 12 or below 1.Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

int acct_num;
    int length_of_sub;
    int year_sub_started;
    int month_sub_started;
    bool month_sub_started_valid = false;
    bool year_sub_started_valid = false;
    bool length_of_sub_valid = false;

do
  {  
    cout <<"Please enter the month (1-12)the subscription started: " << endl;
    cin  >> month_sub_started;
    
         if((month_sub_started >= 1) || (month_sub_started <= 12))
         {
            cout <<"The month your subscription started was: "<<month_sub_started << endl;
            month_sub_started_valid = true;
            }  
         else
            cout <<"Please enter the month between 1 - 12." <<endl;  
   }
   while(month_sub_started_valid == false);




Thank you!
Here is your problem:
(month_sub_started >= 1) || (month_sub_started <= 12)

Consider entering a value for month_sub_started greater than 12:
month_sub_started >= 1 is true, because greater than 12 is greater than 1.
month_sub_started <= 12 is false, obviously.
True or false is equal to true.

Hopefully, you can see that the entire expression can never be false.
Last edited on
Thanks!
I'm pretty new at this, as you can probably tell. Can you expand please on your explanation? I changed the expression to month_sub_started >= 1) || (month_sub_started >= 12, but it still accepts anything greater than 12.

Sometimes it helps to express what you want in English.

For a valid case, you want the number to be greater than or equal to 1 and less than or equal to 12. The key word in that sentence is "and". Just change it to:
month_sub_started >= 1 && month_sub_started <= 12

That is probably what you want.

By the way, logic seems hard to understand at first. The good thing about it is that you don't need to be an expert programmer to understand it. Just remember to consider the precedence of operations and what each operator is telling you.

In this situation you want AND, because you need both comparisons to be true. If you use OR, only one side has to be true, which is why you had a problem.
Last edited on
That was it, now I understand. Thanks so much for the help!
Topic archived. No new replies allowed.