If you don't have a modifiable string, I would use strchr
. Search for the next ,
and then scan like that
#define MAX_LENGTH_OF_NUMBER 9
char *string = "1,5,95,255";
char *comma;
char *position;
// number has 9 digits plus \0
char number[MAX_LENGTH_OF_NUMBER + 1];
comma = strchr (string, ',');
position = string;
while (comma) {
int i = 0;
while (position < comma && i <= MAX_LENGTH_OF_NUMBER) {
number[i] = *position;
i++;
position++;
}
// Add a NULL to the end of the string
number[i] = '\0';
printf("Value is %d\n", atoi (number));
// Position is now the comma, skip it past
position++;
comma = strchr (position, ',');
}
// Now there's no more commas in the string so the final value is simply the rest of the string
printf("Value is %d\n", atoi (position)l