Reputation: 1746
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
Upvotes: 1
Views: 254
Reputation: 13580
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.
Upvotes: 2
Reputation: 50190
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
Upvotes: 3