I have a rather newbie question but I can't figure it out.
Lets say I have this char array:
char array[] = "10,11,12,1,0,1,0";
How can I convert it to an array of int like this?
int arrayINT[] = {10,11,12,1,0,1,0};
1 Answer 1
If you have a C string containing ASCII numbers with a common delimiter (comma in this case) you can use the strtok()
function to split it into individual strings. Then you can use atoi()
to convert those individual strings into integers:
char array[] = "10,11,12,1,0,1,0";
int intArray[7]; // or more if you want some extra room?
int ipos = 0;
// Get the first token from the string
char *tok = strtok(array, ",");
// Keep going until we run out of tokens
while (tok) {
// Don't overflow your target array
if (ipos < 7) {
// Convert to integer and store it
intArray[ipos++] = atoi(tok);
}
// Get the next token from the string - note the use of NULL
// instead of the string in this case - that tells it to carry
// on from where it left off.
tok = strtok(NULL, ",");
}
Note that strtok()
is a destructive function. It will decimate your existing string with NULL characters as it slices it up.
-
Amazing, this is working. I knew about strtok() and atoi() but couldn't get them working properly. Thanks very much!!Houdasek– Houdasek2016年03月22日 11:49:48 +00:00Commented Mar 22, 2016 at 11:49
-
A major improvement would be counting the commas in the string and allocating an array of the approriate size. On the other hand, why not convert the nth value at runtime?ott--– ott--2016年03月22日 22:05:39 +00:00Commented Mar 22, 2016 at 22:05
int arrayINT[] = { 10, 11, 12, 1, 0, 1, 0 }
?