2015-10-14 111 views
-2

以下代码失败,因为atoi()需要char *,我只通过char。我想存储只有第一位数字的值。任何想法我怎么能做到这一点?使用atoi无法接受字符类型 - 任何方式?

int main() { 
    char a[]= "123"; 
    int b = atoi(a[0]); 
    printf("%d",b); 
} 

这里是确切的错误信息:

division.c:9:16: warning: incompatible integer to pointer conversion passing 
     'char' to parameter of type 'const char *'; take the address with & 
     [-Wint-conversion] 
    int b = atoi(a[0]); 
      ^~~~ 
      & 
+0

'的atoi()'旨在字符的空值终止字符串转换;因此,它不适用于单个字符。如果编译器允许你的调用,函数会将字符值解释为一个地址,这不会导致快乐。你已经看到了如何处理一个数字 - 可以说,你应该在应用'a [0] - '0'转换之前检查它是否是一个数字。当然,如果字符串是一个字符串,但atoi()不会返回0,但不能被识别为数字;函数例如'strtol()'告诉你一个值是否被转换,或者是太大,等等。 –

回答

5

呀,单个字符不是字符串为atoi()需要。

如果你只是想要个位数的值,你可以做这样的:

int b = (a[0] - '0'); 
+0

好戏!...! - – cdonts

+0

你到底是怎么做到的......它背后的魔法是什么? – Charana

+0

@Charana'char's被视为像'int','short','long'等任何数字类型,数学就是你所期望的。 ''0'+ 5 =='5'',''a'+ 3 =='d'',最后是''7' - '0'== 7'。 –

相关问题