我得到了这个代码:
char a[151];
scanf ("%150s", a);
在 a
可能是一个数字,如果是这样,我需要确定是否 a < INT_MAX
。我不知道该怎么做,因为在 a
的每个索引中char 可以是一个数字,它意味着 150 位数字,如果我将值存储到某个 int 或其他任何值中,可能会导致溢出。有什么建议吗?
最佳答案
调用strtol()
并测试errno
。
If the correct value is outside the range of representable values,
LONG_MIN
,LONG_MAX
, ... the value of the macroERANGE
is stored inerrno
. C11dr §7.22.1.4 8
char a[151];
scanf ("%150s", a);
char *endptr;
errno = 0;
long num = strtol(a, &endptr, 10);
if (errno == ERANGE) Overflow(); // outside `long` range
if (num > INT_MAX) Overflow(); // greater than `INT_MAX`
关于c - 确定 *char < INT_MAX 是否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33330067/