Search code examples
c++windowsintunsignedcin

Reading 'unsigned int' using 'cin'


I am trying to read an 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 unsigned integer (UINT_MAX), the program displays 3435973836. How do I check if the input given by user falls between 0 to UINT_MAX?


Solution

  • 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.