srgent
srgent

Reputation: 41

strtok keeps returning the same word

I am writing the following program that reads some text from a file. Then I want to divide that text into several piece base on spaces. I used strtok(buffer, " ") to get the first word on the buffer before the space. That part works fine. However after I used strtok(NULL, " ") I get back the same first word. I am expecting to get back the next word. In passing array to the function declared as following char* buffer[BUFFER_SIZE]:

int decoder(char *buffer)
{
    int reg_1 = 0;
    int reg_2 = 0;

    char *tok = strtok(buffer, " "); 

    if(strcmp(tok,"ADD") == 0)
    {
        strtok(NULL, " ");
        puts(tok);

        strtok(NULL, " ");
        puts(tok);
    }            
}

Upvotes: 2

Views: 276

Answers (2)

Nerdy
Nerdy

Reputation: 1099

int decoder(char *buffer)
{
   int reg_1 = 0;
   int reg_2 = 0;

   char *tok = strtok(buffer, " "); 

   if(strcmp(tok,"ADD") == 0)
   {
      puts(tok);
      tok=strtok(NULL, " ");


   }            
}

The returned pointer from strtok() must be assigned to the tok

Upvotes: -2

Brad Budlong
Brad Budlong

Reputation: 1785

You forgot to assign the result of the later calls to strtok(). They should look like:

tok = strtok(NULL, " ");

Upvotes: 5

Related Questions