用char数组填充char数组(char数组到int数组)
问题描述:
我的char数组允许用户输入纯数字字符串,从而将每个数字存储在其自己的数组空间中。我需要将char数组的每个元素分配给int数组中的相应位置。我如何存储实际的数字,而不是与之相当的ASCII码用char数组填充char数组(char数组到int数组)
ex。如果我进入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]);
}
答
变化:
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);
答
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++;
}
}
那辉煌的,但为什么我们需要从焦炭减去 '0'?顺便说一句,修复它,谢谢 – fifamaniac04 2011-04-27 05:30:59
哦,我想出了为什么。当我们将字符9存储到字符串时,它将其存储为ASCII 57,减去字符0(ASCII 48)将导致'9',然后将该值存储在整数中。真棒再次感谢! – fifamaniac04 2011-04-27 05:37:02