I'm sorry I didn't understand your reply (my fault I believe). Let me discuss from a different angle:
if I make x a signed short, the program detects failure fine: range -32767 to +32767. If x falls out of the range, cin.fail occurs. If I make x an unsigned short 0 to 65535, negative numbers still pass; cin.fail not triggered.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
int main()
{
//unsigned short x;
unsignedshort x;
//std::cin>>x;
std::cin>>x;
if (std::cin.fail())
{std::cin.clear(); //flags
std::cout<<"fail";
std::cin.ignore(32767, '\n'); //
}
else
{std::cout<<"no fail"<<std::endl;}
}
What behavior do you expect, and why? Did some documentation incorrectly specify the result of passing a negative integer string into the unsigned operator>>?
In general, unsigned integers never overflow, they wrap around instead, and so unsigned "overflow" is never treated as an error. Signed integers overflow, resulting in undefined behavior. It is always an error to overflow a signed integer, so when signed operator>> would overflow, it sets the failbit.
As you know, when you are inputting an unsigned, even if you input a negative, the present number is still actually in the valid range of [0..65535]. That's why (cin) never sets fallbit even when you input a negative number for an unsigned.
Because the relevant case involves undefined behavior.
As you know, when you are inputting an unsigned, even if you input a negative, the present number is still actually in the valid range of [0..65535]. That's why (cin) never sets fallbit even when you input a negative number for an unsigned.
If you input a negative number, the value is clearly not in the range [0, 65535], so it isn't terribly intuitive that it is quietly converted for you.