Hello,
I'm having some troubles working with strtok. I'm having a string of numbers I want to put in an array, and say from the list I want to get an array with 1,3,5,6,7,8,9,10,12,13,14.
First I just wanted to see the single numbers in one place and split that 5-9 in another place as it would need to be treated differently. But after the first 5-9, where it splits the 5-9, properly into 5 and 9, it doesn't do anything more.
Probably ain't the most efficient code, but been trying to make it work one way or another, so thats why i got all those printfs.
Why is pch going NULL where as with no "if" code, it properly parses the whole string by ",".
/* test for input of a list */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str[]="1,3,5-9,10,12-14";
char *pch;
char *pch1;
char *temp;
int i;
pch = strtok(str,",");
while (pch != NULL)
{
printf("debug0 %s\n",pch);
temp = strdup(pch);
pch1 = strchr(temp,'-');
printf("debug1 %s\n",temp);
printf("debug2 %s\n",pch);
if (pch1 != NULL)
{
pch1 = strdup(temp);
pch1 = strtok(pch1,"-");
while (pch1 != NULL)
{
i = atoi(pch1);
printf("p %d\n",i);
pch1 = strtok(NULL,"-");
}
printf("debug3 %s\n",pch);
}
else {
i = atoi(pch);
printf("%d\n",i);
}
free(temp);
free(pch1);
printf("debug5 %s\n",pch);
pch = strtok(NULL,",");
printf("debug6 %s\n",pch);
}
return 0;
}