tariq
tariq

Reputation: 529

problem in strtok function

hi every one i have an array

21 44 56 777

i am using strtok function to seperate them on the basis of space

int i;
char *token;
token = strtok(payload1, " ");
printf ( "\n\n\nTOKEN  %s" , token);

i works fine that is it displayed 21. now i want display 44 using the same variable token how to do that

thanks kindly help me

Upvotes: 0

Views: 663

Answers (3)

gatoAlfa
gatoAlfa

Reputation: 130

the implementation of strtok saves the pointer to the string in a private variable on the first call. On subsequent calls that the first parameter is NULL it will return the next token of initial string.

Since strtok uses some private storage to save the pointer you can not process two different strings simultaneously, and it is not reentrant.

If you want to sue strtok use the reentrant version, strtok_r that is safer even if you are not running multiple treads.

for example if function A is using strtok to parse a string and in the middle of it calls another function that also uses strtok to parse another string, function A will get the wrong result.

Also keep in mind that strtok modifies the string, ergo cannot be used on static allocations.

Upvotes: 0

p4553d
p4553d

Reputation: 818

try this

while(token != NULL){
   token = strtok(NULL, " ");
}

Upvotes: 0

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22064

You will need to repeatedly apply strtok.

token = strtok(payload1, " "); 
while ( token != NULL)
    {
    token = strtok(NULL, " ");
    // do your stuffs
    }

Upvotes: 3

Related Questions