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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 <string.h>
#include <stdio.h>

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;
}
//output

Hello there
Dave
this is your computer speaking.

Share this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites