Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 390
user1250836 Avatar asked Mar 05 '12 22:03

user1250836


People also ask

Does C++ have unsigned int?

C++ also supports unsigned integers. Unsigned integers are integers that can only hold non-negative whole numbers. A 1-byte unsigned integer has a range of 0 to 255. Compare this to the 1-byte signed integer range of -128 to 127.

Does unsigned int include 0 C++?

Unsigned int data type in C++ is used to store 32-bit integers. The keyword unsigned is a data type specifier, which only represents non-negative integers i.e. positive numbers and zero.

Can we use CIN for char?

Cin With Member Functionsget(char &ch): Reads a character from the input and stores it in ch. cin. getline(char *buffer, int length): Reads a stream of characters into the string buffer, stopping when it reaches length-1 characters, an end-of-line character ('n'), or the file's end.


2 Answers

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.

like image 182
JvO Avatar answered Sep 16 '22 20:09

JvO


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.

like image 41
PlasmaHH Avatar answered Sep 19 '22 20:09

PlasmaHH