Populate int array with a char array full of numbers in C (char array to int array)
My Char array allows for a user to input a purely numeric string, thus storing each digit in its own array space. I need to assign each element of the char array to the corresponding location in the int array. How do i store the actual numeral rather than the the ASCII equivalent
ex. if I enter 9 as the string, i don't want 57 (the ASCII value) 开发者_Go百科but the numeral 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]);
}
Change:
x[i] = ((int)temp1[i]);
y[i] = ((int)temp2[i]);
to:
x[i] = temp1[i] - '0';
y[i] = temp2[i] - '0';
Note that you also need to fix your scanf
calls - change:
printf("Please enter a number: ");
scanf("%s", &temp1);
printf("Please enter second number: ");
scanf("%s", &temp2);
to:
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++;
}
}
精彩评论