Matthew Matthew - 2 months ago 50
C Question

C - Detect Integer Overflow in Input

Is there a way in C or C++ to check whether the number provided by the user is outside the range of an integer type?

For instance, let us assume that we are using 16-bit signed integers with a range of -32768 to 32767.

If the user enters 55555 into the program, this will be wrapped to become a negative number so that if you are using a function which can accept any number, the result would be wrong.

Is there a way in C or C++ to determine whether the number provided by the user is within the range of the integer type?




Update: I am using the numbers in a simple subtraction program which accepts two numbers and subtracts the second from the first.

Answer

If the user enters 55555 into the program, this will be wrapped to become a negative number

Not always. It depends upon how you read the number. If you use, operator>>, for example, that value will not be wrapped, it will be rejected.

Is there a way in C or C++ to determine whether the number provided by the user is within the range of the integer type?

In C++, just use operator>>:

#include <iostream>
int main() {
  signed short int i;
  std::cin >> i;
  if(std::cin)
    std::cout << "You entered a valid number!\n";
  else
    std::cout << "Aw c'mon, play by the rules.\n";
}
Comments