New in C and pretty confused about how to deal with several strings at the same time using strtok, for a simply example, I want to use strtok to extract the number and compare then.
#include <stdio.h>
#include <string.h>
int main()
{
char s1[100]="11.54";
char s2[100]="12.55";
const char tok[2]=".";
char* token1=strtok(s1,tok);
char* token2=strtok(s2,tok);
while(token1 !=NULL && token2 !=NULL){
int temp=strcmp(token1,token2);
if(temp==0){
token1=strtok(NULL,tok);
token2=strtok(NULL,tok);
}
else if(temp<0){
printf("%d\n",-1);
return;
}
else{
printf("%d\n",1);
return;
}
}
if(token1 !=NULL){
printf("%d\n",1);
return;
}
if(token2 !=NULL){
printf("%d\n",-1);
return;
}
printf("%d\n",0);
return 0;
}
But when I use the strtok, the strtok(NULL,token)will point to the current string and will do like: 11->12>55->NULL and skip the 54
How could I deal with such situation? Thanks!!
Do not use
strtok()
. The documentation will tell youstrtok()
is not reentrant (i.e. should not be used across threads), but perhaps less obvious is the fact that the reason it is not reentrant is because it uses an internalsave
variable to remember where it's got to. That means you also can't use two instances at once. Instead usestrtok_r()
or failing thatstrsep()
might work.strtok_r()
is just likestrtok
, save that you pass it achar **
(i.e. a pointer tochar *
) where it can save where it's got to.The GNU libc manual page gives a good example of using a nested
strtok_r
which is what you are trying to do: