检测输入中的整数溢出 [英] Detect Integer Overflow in Input
问题描述
在C或C ++中是否有办法检查用户提供的数字是否超出整数类型的范围?
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?
例如,让我们假设我们正在使用范围为-32768到32767的16位有符号整数。
For instance, let us assume that we are using 16-bit signed integers with a range of -32768 to 32767.
如果用户输入55555进入程序,这将被包装成负数编号,这样如果你使用的函数可以接受任何数字,结果就会出错。
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.
在C或C ++中是否有办法确定是否提供了数字用户是否在整数类型的范围内?
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.
推荐答案
如果用户输入55555进入程序,这将被包装成负数
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.
在C或C ++中是否有办法确定用户提供的数字是否在整数类型的范围内?
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?
在C ++中,只需使用运算符>>
:
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";
}
这篇关于检测输入中的整数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!