使用C中充满数字的char数组填充int数组(char数组到int数组)

时间:2011-04-27 05:14:13

标签: c arrays char int

My Char数组允许用户输入纯数字字符串,从而将每个数字存储在自己的数组空间中。我需要将char数组的每个元素分配给int数组中的相应位置。如何存储实际数字而不是ASCII等价

离。如果我输入9作为字符串,我不想要57(ASCII值),而是数字9。

int main()   
{

    int x[256] = {0};
    int y[256] = {0};

    char temp1[256] = {0};
    char temp2[256] = {0};

    char sum[256] = {0};
    printf("Please enter a number: ");
    scanf("%s", &temp1); 

    printf("Please enter second number: ");
    scanf("%s", &temp2);

    for(i=0; i<256; i++)
    {
        x[i] = ((int)temp1[i]);
        y[i] = ((int)temp2[i]);         
    }

2 个答案:

答案 0 :(得分:2)

变化:

    x[i] = ((int)temp1[i]);
    y[i] = ((int)temp2[i]);         

为:

    x[i] = temp1[i] - '0';
    y[i] = temp2[i] - '0';         

请注意,您还需要修正scanf来电 - 更改:

printf("Please enter a number: ");
scanf("%s", &temp1); 

printf("Please enter second number: ");
scanf("%s", &temp2);

为:

printf("Please enter a number: ");
scanf("%s", temp1); 

printf("Please enter second number: ");
scanf("%s", temp2);

答案 1 :(得分:0)

int main(void) {
int x = 0;
int y = 0 
char input[12] = {0}; --->initialize var input 


scanf("%s", &input[0]);
int ch_len = strlen(input)/sizeof(char); --create length of input[] array
int digit[ch_len];    --->initialize digit which size is how many character in input[] array
fflush(stdin);

while (input[y] != '\0') {
if (isdigit(input[y])) {
    digit[x++] = input[y++]-'0';
    count++;
}
else y++;
}
}