Reading 'unsigned int' using 'cin'

孤人 提交于 2019-12-01 17:37:18
JvO

Two things:

  • Checking if an unsigned integer is < 0 or > UINT_MAX is pointless, since it can never reach that value! Your compiler probably already complains with a warning like "comparison is always false due to limited range of type".

  • The only solution I can think of is catching the input in a string, then use old-fashioned strtoul() which sets errno in case of overflow.

I.e.:

#include <stdlib.h>

unsigned long number;
std::string numbuf;
cin >> numbuf;
number = strtoul(numbuf.c_str(), 0, 10);
if (ULONG_MAX == number && ERANGE == errno)
{
    std::cerr << "Number too big!" << std::endl;
}

Note: strtoul returns an unsigned long; there's no function strtou(), returning an unsigned int.

Your check makes no sense (which a compiler with properly enabled warnings would tell you) as your value is never under 0 and never over UINT_MAX, since those are the smallest and biggest value a variable of the type unsigned int (which number is) can hold.

Use the stream state to determine if reading into the integer worked properly.

You could read into an unsigned long long and test that against the unsigned int limit.

When users enter a number higher than UINT_MAX, cin caps it at UINT_MAX anyway. The value cannot be negative, either.

If you need to extend the range, use unsigned long long for input, and cast to unsigned int after the check. This will not guard against numbers that are outside of range of unsigned long long, though.

For a general-purpose solution, you can read a string, and do a conversion yourself using unsigned long long as your result.

If you try to read it into an unsigned int you are going to have to limit yourself to the constraints of an unsigned int.

The most general way to do what you're asking is to read the input as a string and parse it to make sure it's in the proper range. Once you have validated it, you can convert it to an unsigned int.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!