Reading 'unsigned int' using 'cin'

I am trying to read unsigned int using cin as follows:

 #include <limits.h> #include <iostream> using namespace std; int main(int argc, char* argv[]) { unsigned int number; // UINT_MAX = 4294967295 cout << "Please enter a number between 0 and " << UINT_MAX << ":" << endl; cin >> number; // Check if the number is a valid unsigned integer if ((number < 0) || ((unsigned int)number > UINT_MAX)) { cout << "Invalid number." << endl; return -1; } return 0; } 

However, whenever I enter a value greater than the upper limit of an unsigned integer ( UINT_MAX ), the program displays 3435973836 . How to check if user input is between 0 and UINT_MAX ?

+6
source share
5 answers

Two things:

  • Checking whether an unsigned integer is <0 or> UINT_MAX is pointless since it can never reach this value! Your compiler may already be complaining about a warning, such as "the comparison is always incorrect due to a limited range of types."

  • The only solution I can think of is to capture the input in a string and then use the old-fashioned strtoul (), which sets errno in case of an 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 is no strtou () function returning an unsigned int.

+5
source

Your check does not make sense (as the compiler will tell you with warnings correctly turned on), since your value is never under 0 and never exceeds UINT_MAX, since this is the smallest and largest value of a variable of type unsigned int (which is a number).

Use the stream state to determine if an integer is being read correctly.

+3
source

You can read unsigned for a long time and check that the unsigned int limit is against the limit.

+2
source

When users enter a number higher than UINT_MAX , cin closes it at UINT_MAX . The value also cannot be negative.

If you need to expand the range, use unsigned long long for input and enter unsigned int after verification. This will not protect against numbers that are outside the range of unsigned long long .

For a universal solution, you can read string and do the conversion yourself, using unsigned long long as the result.

+2
source

If you try to read it in unsigned int , you will have to limit yourself to the limitations of unsigned int .

The most common way to do what you ask is to read the input as a string and parse it to make sure it is in the correct range. After you confirm it, you can convert it to unsigned int .

+1
source

Source: https://habr.com/ru/post/910033/


All Articles