views:

138

answers:

2

Why is my strtok breaking up my strings after space when I specified my delimiter as ","?

+6  A: 

I can only suggest that you're doing something wrong though it's a little hard to tell exactly what (you should generally post your code when asking about specifics). Sample programs, like the following, seem to work fine:

#include <stdio.h>
#include <string.h>

int main (void) {
    char *s;
    char str[] =
        "This is a string,"
        " with both spaces and commas,"
        " for testing.";
    printf ("[%s]\n", str);
    s = strtok (str, ",");
    while (s != NULL) {
        printf ("   [%s]\n", s);
        s = strtok (NULL, ",");
    }
    return 0;
}

It outputs:

[This is a string, with both spaces and commas, for testing.]
   [This is a string]
   [ with both spaces and commas]
   [ for testing.]

The only possibility that springs to mind immediately is if you're using " ," instead of ",". In that case, you would get:

[This is a string, with both spaces and commas, for testing.]
   [This]
   [is]
   [a]
   [string]
   [with]
   [both]
   [spaces]
   [and]
   [commas]
   [for]
   [testing.]
paxdiablo
A: 

Thanks! I looked around and figured out that the problem was with my scanf which doesn't read the whole line the user inputs. It seems that my strtok was working fine but the value i am using to match the return value of strtok is wrong. For example, my strtok function takes "Jeremy whitfield,Ronny Whifield" and gives me "Jeremy Whitfield" and "Ronny Whitfield". In my program, i am using scanf to take in user input > "Ronny Whitfield" which is actually only reading "Ronny". So its a problem with my scanf not strtok. My virtual machine is getting stuck everytime i open it so i am unable to access my code for now.

svenus
I'm just glad you're using C and not some other crap.
Matt Joiner
As an aside, you should _never_ use `scanf` to input a string where you don't control the size. That's asking for trouble in terms of buffer overflows. Either use `scanf` with a specific length or `fgets` with a maximum length (the latter is my preference).
paxdiablo