gpt4 book ai didi

c - 通过从 char * 转换为 int 进行整数验证

转载 作者:行者123 更新时间:2023-11-30 18:24:07 24 4
gpt4 key购买 nike

假设我有一个无效的整数输入到 char * 其中,

char *ch = "23 45"

使用atoi(ch)给出23作为转换后的输出,忽略空格和45。

我正在尝试对此输入进行测试。我该怎么做才能将其标记为无效输入?

最佳答案

要么在将字符串传递给 atoi() 之前检查字符串,要么使用 strtol(),尽管后者将返回 long int

使用strtol(),您可以检查错误:

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

ERRORS
EINVAL (not in C99) The given base contains an unsupported value.

ERANGE The resulting value was out of range.

The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned).

关于c - 通过从 char * 转换为 int 进行整数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44266934/

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