1

I ran across a problem where I need to extract each element of string to an integer array, the string only contains integer values without any space or delimiter.

Here is an example.

char input[8]="02320000";

to

int output[8]={0,2,3,2,0,0,0,0};

I tried to use the atoi() and it is taking the entire string as digit.

The string characters will be 0-3.

thank you

Dilip Kumar
  • 1,736
  • 11
  • 22

2 Answers2

3
char input[8]="02320000";
int output[8];

for(int i = 0; i < 8; i++)
{
     output[i] = input[i] - '0';
}

explanation of the -'0' Convert a character digit to the corresponding integer in C

pm100
  • 48,078
  • 23
  • 82
  • 145
  • This got me thinking about end of string and char array initialization, so I played with it a little bit. I learned that "02320000" seems to get implicitly cast to either (char [8]) or (char [9]) depending on whether input is char input[8] or char input[9]. I didn't expect a size of both 8 and 9 to work as seamlessly as it did. For 8, it does not terminate the string, for 9, it does. Of course you can't use anything smaller than 8 for the array size. – Stephen Docy Jan 30 '18 at 01:45
2

Well, you can loop through all characters of the string:

char input[8]="02320000";
char output[8];

for(int = 0; i < 8; ++i)
    output[i] = input[i] - '0';

Strings in C are just sequences of characters that ends with the so called '\0'-terminating byte, whose value is 0. We use char arrays to store them and we use the ASCII values for the character.

Note that 1 != '1'. 1 is the interger one, '1' is the representation of the number one. The representation has the value 49 (see ASCII). If you want to calculate the real number of a character representation, you have to use c-'0', where c is the character in question. That works because in the table, the values of the numbers also are ordered as the numbers themselves: '0' is 48, '1' is 49, '2' is 50, etc.

Pablo
  • 13,271
  • 4
  • 39
  • 59