climits USHRT_MAX not working

I'm trying to have the user input a value into an unsigned short, and if they input a value that's greater than the maximum value for that data type, then the program will notify that an error has occurred. To do this, I'm making use of the climits header, which you can see here:
http://www.cplusplus.com/reference/climits/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <climits>

int main()
{
	unsigned short num;

	while (true)
	{
		std::cin >> num;

		if (num > USHRT_MAX || num < 0)
		{
			std::cout << "Error" << std::endl;
		}
		else if (num > 0 && num < USHRT_MAX)
		{
			std::cout << num << std::endl;
		}
	}

	system("pause");
	return 0;
}


Whenever I try to input a value over 65535 or below 0 (which are the bounds of an unsigned short can hold) it doesn't display "Error", but instead displays a glitch value of sorts.
Whenever I input a value within the bounds of an unsigned short, it does work as expected.

I think it could be that when an invalid value is input into a data type that doesn't allow it, the value is re-initialized by the software so that it can be within the bounds as a valid value, though some clarification would be nice.

How can I fix the program? Is there any way I can make it so that (perhaps through the use of exceptions) the value isn't re-initialized and just doesn't get inputted into the variable in the first place?

Thank you in advance.
It is impossible that num can be greater than its greatest number. It is also impossible that an unsigned value is less than 0.

You need a type that has a greater range of number (like signed long) which can fullfill the condition on line 12
You're not understanding what I'm saying. I want it so that should the user input a number greater than its greatest number, or a value below 0, the user will be notified.
But the program isn't noticing when an invalid number is input.
And you're not understanding what coder777 is telling you. Since you refer to 65535, we know that an unsigned short is 16 bits. The largest value that can be represented in 16 bits is 65535 (all 16 bits are 1). How can you possibly have a larger number? Likewise, since there is no sign bit, it is impossible to represent a negative number.

As coder777 suggested, if you want to test for a number that is bigger than will fit in an unsigned short, use a larger type then compare that larger type to the limits for an unsigned short.
1
2
3
4
5
6
7
8
9
10
11
   long temp;
   unsigned short num;
   
  cin >> temp;
  if (temp > USHRT_MAX || temp < 0)
  {  //  Won't fit in an unsigned short, tell the user
  }
  else
  { //  We know it will fit
    num = (unsigned short)temp;
  }

Last edited on
Topic archived. No new replies allowed.