gpt4 book ai didi

检查 C 中的 long long 溢出

转载 作者:行者123 更新时间:2023-11-30 20:50:36 33 4
gpt4 key购买 nike

我想检查 fgets 中的变量没有溢出ling long int在C语言中。我试过这个:

long long x; 
fgets(...)
...
if(x <= LLONG_MAX && x >= LLONG_MIN)

但它不起作用,因为 long long int将收到过多的数量;它返回LLONG_MIN + 过量(我认为是这样)。

最佳答案

当您尝试从 char* 转换为 long long 时,请使用 strtoll。这些行取自 strtoll 文档 (strtoll):

The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX. In both cases, errno is set to ERANGE. Precisely the same holds for strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX).

关于检查 C 中的 long long 溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42636688/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com