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};
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.
int arrayINT[] = { 10, 11, 12, 1, 0, 1, 0 }?