首页 > 解决方案 > 不知道为什么我不能从字符串转换为整数?

问题描述

string typeVisa (string str);    

int main(){
        string credit_card;
        string type;

        getline(cin, credit_card);
        type = typeVisa(credit_card);
    }

string typeVisa (string str){

    int digit1;
    int digit2;

    digit1 = atoi(str[0]);
    digit2 = atoi(str[1]);
    // code continues and returns a string

}

“char”类型的参数与“const char *”类型的参数不兼容这是什么意思^^?

标签: c++type-conversion

解决方案


atoi()接受一个以空字符结尾的字符串,但您试图将其传递给单个字符。你可以这样做:

char arr[] = {str[0], '\0'};
digit1 = atoi(arr);

arr[0] = str[1];
digit2 = atoi(arr);

...

但是将char范围内'0'..'9'的 a 转换为等值整数的更简单方法是'0'从字符中减去,因此:

'0' - '0' = 48 - 48 = 0
'1' - '0' = 49 - 48 = 1
'2' - '0' = 50 - 48 = 2
And so on...
digit1 = str[0] - '0';
digit2 = str[1] - '0'; 

推荐阅读