如何检查用户输入的数字不大于LLONG_MAX或小于LLONG_MIN? [英] How to check that an user inputted number isn't bigger than LLONG_MAX or LOWER than LLONG_MIN?

查看:203
本文介绍了如何检查用户输入的数字不大于LLONG_MAX或小于LLONG_MIN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查用户输入的数字是否大于或小于告知的值.

I want to check if an user inputted number is bigger or lower than the told values.

我了解 atoll函数,但似乎没有为了特别有用,将检查基于未定义的值似乎不太有说服力.

I know about atoll function but it doesn't seem to be specially helpful, basing the check on a undefined value doesn't look too convincing.

我也知道我可以检查用户输入的字符串是否全为数字,在这种情况下,我可以检查一下字符串的长度是否大于LLONG_MAXLLONG_MIN的长度删除了左侧的0,或者在两者的长度相同的情况下,我可以逐位检查数字,并且如果该数字中输入的数字的值大于LLONG_MAXLLONG_MIN的值,它会超出范围.

I also know that I could check if the string the user has inputted is all digits, in this case I could check for things as if the length of the string is bigger than the length of LLONG_MAX or LLONG_MIN once 0s on the left are removed, or in the case the length of both is the same I could go checking digit by digit and if the value of the inputted number in that digit is bigger than the value of LLONG_MAX or LLONG_MIN the it would be out of range.

但是我想必须有一个更好的方法来做到这一点.希望您能给我有关哪种方法的提示.

But I guess there has to be a better way to do this. Hope you can give me tips about which that way is.

推荐答案

请改用strtoll函数.

如果输入的值超出范围,则将errno设置为ERANGE,并根据值是下溢还是上溢返回LLONG_MINLLONG_MAX.

In case the inputted value is out of range, errno is set to ERANGE and either LLONG_MIN or LLONG_MAX are returned, depending on whether the value underflows or overflows.

手册页中:

strtol()函数返回转换结果,除非 该值将下溢或上溢.如果发生下溢, strtol()返回LONG_MIN.如果发生溢出,strtol() 返回LONG_MAX.在这两种情况下,errno都设置为ERANGE.恰恰 对于strtoll()也是一样(对于LLONG_MINLLONG_MAX 而不是LONG_MINLONG_MAX).

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).

这篇关于如何检查用户输入的数字不大于LLONG_MAX或小于LLONG_MIN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆