Advertisement

Problem using strtok.

Started by June 11, 2001 04:08 PM
2 comments, last by kharris 23 years, 8 months ago
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
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;}//outputHello there Dave this is your computer speaking.  
Advertisement
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
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.

This topic is closed to new replies.

Advertisement