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.