Converting a string into an int array
30,425
Solution 1
scanf("%s", &string[0]);
read into input
character array. you are reading into some other variable.
scanf("%s",input);
or even best
fgets(input,sizeof input, stdin );
digit[x++] = input[y++]-'0';
// substract `'0'` from your character and assign to digit array.
For example if input[i]=='3'
==> '3'-'0'
will result in integer digit 3
Solution 2
I would suggest you to use strtol or sscanf in a loop. That would make things easier for you.
Something like this:
char *c = "12 23 45 9";
int i[5];
sscanf(inputstring, "%d %d %d %d %d", &i[0], &i[1], &i[2], &i[3], &i[4]);
Sample example using atoi() which another option:
int main(int argc,char *argv[]){
char y[10] = "0123456789";
char x[3];
int i;
x[0] = y[8];
x[1] = y[9];
x[2] = '\0';
i=atoi(x);
}
Author by
Niels Robben
Updated on August 29, 2020Comments
-
Niels Robben over 3 years
While programming in C I got stuck at the following code-snippet:
While converting from char array
input
to integer arraydigit
, only the ANSI code is converted to the digit array.How can I make sure the correct integer-value is given to this array ?
This is the relevant code:
int main(void) { int x = 0; int y = 0 char input[12] = {0}; int digit[12] = {0}; scanf("%s", &input[0]); fflush(stdin); while (input[y] != '\0') { if (isdigit(input[y])) { digit[x++] = input[y++]; count++; } else y++; } }