2017-05-30 41 views
-1

说我有一个无效的整数输入到一个char *其中,整数验证为int

char *ch = "23 45" 

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

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

+2

,我建议使用['strtol'](http://en.cppreference.com/w/c/string/byte/strtol),因为它允许验证。 –

+1

https://stackoverflow.com/q/13199693/971127 – BLUEPIXY

+0

scanf()及其朋友是邪恶的。我在这种情况下使用fgets(...)@BLUEPIXY – ekeith

回答

3

在将字符串传递给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). 
+2

同样重要的是返回值是中间参数,因为它允许检查它是否转换整个字符串。 –

+0

如何使用atoi()来指示输入是否可用 – ekeith

+0

只需循环它并检查它是否仅包含数字(如果您接受负数整数,也许'-'作为第一个符号)。 – syntagma

2

缺乏错误检测是的atoi()功能的主要缺陷之一。如果这是你需要的,那么基本的答案是“不要使用atoi()”。

strtol()函数几乎在任何方面都是更好的选择。为了您的特定目的,您可以传递一个指向char *的指针,其中它将记录指向输入中未转换的第一个字符的指针。如果整个字符串转换成功则指向字符串结束将被保存,所以你可以写

_Bool is_valid_int(const char *to_test) { 
    // assumes to_test is not NULL 
    char *end; 
    long int result = strtol(to_test, &end, 10); 
    return (*to_test != '\0' && *end == '\0'); 
}