DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: Problem with strtok function when tokenizing user input

1. Registered User
Join Date
Nov 2006
Location
Orlando, Florida
Posts
1

## Problem with strtok function when tokenizing user input

Hi, everyone. I am new to this forum, and I hope that through time, I will be able to help out this community in any way I can.

First, though, I have a quick question pertaining to C language, particularly the strtok function. I am creating a program to differentiate a user-defined equation and return the derivative to the main function (or print it out in the void function). I am permitting the user (for now) only to enter polynomial equations of the second degree (eg x^2 +2x +2). I created a function that is supposed to split up the equation initially by using the 'space' character as the delimiter. to test, i tried to print out each token as it was parsed by strtok. However, after the first item has been tokenized, the second and third characters are returned from the strtok function as (null). Here is an example:

Output:
token1 = x^2
token2 = (null)
token3 = (null)

How do I get the strtok function to recognize subsequent values after x^2? Here is the code for the derivative function i am using:

void derive(){
char equation[50];
const char delim1[] = " ", delim2[] = "x ^";
char derivative[50];
char *tok1, *tok2, *tok3;

scanf("%s", &equation);

tok1 = strtok(equation, delim1);
printf("token1 = %s\n", tok1);
tok2 = strtok(NULL, delim1);
printf("token2 = %s\n", tok2);
tok3 = strtok(NULL, delim1);
printf("token3 = %s\n", tok3);

...

system("PAUSE"); //this is for testing purposes, not in final version

}

2. Senior Member
Join Date
Dec 2003
Posts
3,366
you need to grab the position of the space and pass the rest of the string to strtok, not NULL. Passing null to the function instead of a string means it got an empty string, which wont really do much.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise