#### Archived

This topic is now archived and is closed to further replies.

# Problem using strtok.

This topic is 6028 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a small problem. I am tokenizing a comma delimited list of data, and each piece of data can consist of just about any ASCII character (except ","). The problem I am having is that if any piece of data includes a space character " ", the strtok returns only the part before the space and then it completely throws off the rest of the strtok''s and stops reading \n''s and stuff. Anyone know why strtok might have a problem with " "? Thanks, kharris

##### Share on other sites
Either you''re including space as a separator, or those aren''t really spaces--they''re nulls. strtok can''t go through nulls.

Here''s a sample program and its output:
  #include #include int main (){ char stg[] = "Hello there, Dave, this is your computer speaking."; const char sep[] = ","; char *token = strtok (stg, sep); while (token) { printf ("%s\n", token); token = strtok (NULL, sep); } return 0;}//outputHello there Dave this is your computer speaking.

##### Share on other sites
Do you suppose reading from a file would make a difference? I am using the vi editor in UNIX and instead of using a const char[] to declare my delimiter, i am just passing ",". I don''t know if either of these makes a difference, but the sample code you supplied, which is what is basically at the core of my program, works just fine.

Thanks for the help so far, though.
kharris

##### Share on other sites
hm, really should have made it a static const char. =) I just try to heap on as many qualifiers as possible.

If you''re just passing in ",", with no spaces, then it should compile to the same code. I''m a little confused about your reply: are you saying the code I wrote works fine in your program? If so, you were using strtok incorrectly. If, however, you put my code in your program and it does not work fine, I have a feeling that you have nulls in your file. Open up your file in a hex editor if you can and take a good look at it as strtok moves along.

• ### Forum Statistics

• Total Topics
628667
• Total Posts
2984136

• 12
• 9
• 10
• 9
• 9