Regarding infinite loop with cin and while

Hey there experts and gurus.
I wanted to ask about the code i have used below here.
I wanted to only allow 1 to 12 numbers,since it only has month 1 until 12 right.
I was wondering, when i tried to enter an alphabet, it goes into infinite loop.
been trying for a couple of days already got quite frustrated and decided to ask on this forums :)

I hope you guys would help me out thanks!

1
2
3
4
5
6
7
8
		cout << "How long do you want to extend your membership? [1-12 mths] : ";
		cin >> m;
		while (m <= 0 || m > 12 && !((m > 0)) || !((m < 12))) 
		{
			cout << "Invalid! Please enter a number between 1 to 12 : ";
			cin.clear();
			cin >> m;
		}


Regards,
error0024
I think you may have your logic mixed up a little:
1
2
3
4
5
while(m <= 0)
// and
while(!(m>0))
// is the exact same.
//Likewise for m > 12 and !(m < 12)  (Except that in this case only the second one will allow 12) 

Therefore your while condition can simply be written as
 
while( m <= 0 || m > 12) //since "anding" this with the exact same condition will give you the same answer :P 

Why are you testing for numbers less than 0 and greater than 12?
Also,under ASCII representation all letters are larger than 12 if treated as an int.

EDIT:
Grammar
Last edited on
Instead of casting your input directly as an integer, you may want to cast it to a character array, use std::atof(), then cast to integer. This will successfully round down doubles and treat non-number characters as '0'.
Topic archived. No new replies allowed.