Detect Integer Overflow in Input

烂漫一生 提交于 2020-01-06 07:53:58

问题


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.


回答1:


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";
}



回答2:


If you're using something like strtol it'll set errno to ERANGE if an overflow occurs




回答3:


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?

It depends of what function you are using (strtol can do that for example). Check the documentation.




回答4:


The only difference between int's and uint's is how INTERPRET them. Your problem has no solution, if it so critical for you consider switching to floating point argument, checking value and typecasting. Update: I thought you want run time check function argument value provided by another programmer, not console input.



来源:https://stackoverflow.com/questions/12938053/detect-integer-overflow-in-input

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