c - Parsing a string separated by commas works only once? -


i have menu when press 'a' following code parses numbers separated commas. first time press 'a' results 100% accurate. second+ times press 'a' menu repeat same code, strange results. using mplab c18 compiler pic18

i using mplab c18 compiler pic18

first time output

0002

0100

0200

0100

second+ times output

0002

code

char somestr[] ="2,0100,0200,0100"; char *pt; int a; pt = strtokpgmram (somestr,",");  while (pt != null)  {     = atoi(pt);     printf("%d\n", a);     pt = strtokpgmram (null, ","); } 

how fix every time press 'a' menu same results first time output?

thank you!

this because, calling strtok() change original string itself. have make copy of original string before calling strtok().

i made sample program understanding.

see, in tokenize function, everytime making copy , using copy.

#include<stdio.h> #include<string.h>  void tokenize(char* s){      char *pt;     int a;      char* copy_somestr = malloc((strlen(s)+1) * sizeof(char));     strcpy(copy_somestr,s);      pt = strtok (copy_somestr,",");      while (pt != null)     {         = atoi(pt);         printf("a = %d somestr = %s\n", a,s);         pt = strtok (null, ",");     }      free(copy_somestr); } void main(){     char somestr[] ="2,0100,0200,0100";       /*     printf("beginning somestr = %s",somestr);     // if tokenize here without making copy using somestr, still works after call somestr become unusable.     printf("afterlast somestr = %s",somestr);     */       tokenize(somestr);       // still use somestr     printf("i still use somestr = %s\n",somestr);       tokenize(somestr);    } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -