0

I have a function that takes a string. I make a copy of the string and a char *token;. I say token = strtok(myString, " "); and then start a while loop with while(token != NULL) {...}, and I do some stuff in the while loop. At the end of the while loop I say token = strtok(NULL, " "); which seems to follow examples I've seen online. My input string is "this is a string I will mess with" and my first token is "this" which is great, but then after I say token = strtok(NULL, " "); token appears to be "(null)" instead of "is". I am wondering why. Here is my code:

int numReps2(char *s) {
    printf("inside numReps2 with \"%s\"\n", s);
    // iterate through s until you find a space
    // do matchingwords with the word and an accumulator string that you build char x char
    int l = mystrlen(s);
    char *copy = malloc(1+(sizeof(char) * l));
    mystrcpy(copy, s);

    char *accu = malloc(1+(sizeof(char) * l));

    int ret = 0;
    printf("about to tokenize \"%s\"\n", copy);

    char *token;
    const char delim[2] = " ";

    token = strtok(copy, delim);
    while(token != NULL) {
        if(matchingWords(accu, copy)) {
            printf("match-> accu is \"%s\" and token is \"%s\"\n", accu, token);
            // we have a match
            ret++;
        } else {
            // no match, add to accu
            char *temp = mystrappend(token, " ");  // stick a space after it
            printf("no match, adding \"%s\" to \"%s\", token is still \"%s\"\n", temp, accu, token);
            accu = mystrappend(accu, temp);
            printf("accu is now \"%s\"\n", accu);
            free(temp);
            printf("after freeing temp, token is \"%s\"\n", token);
        }
        printf("here is what's after token: %c\n", *(token+strlen(token)+2));
        token = strtok(NULL, delim);
        printf("just tok'd again, now it's \"%s\"\n", token);
    }

    free(copy);
    free(accu);
    return ret;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Aaron Parisi
  • 464
  • 7
  • 15
  • 1
    Does `mystrappend()` use `strtok()`, perchance? Or `matchingWords()`? With `strtok()`, no function that calls your code can be currently using `strtok()`, nor can any function that you call use `strtok()`. Use `strtok_s()` on Microsoft and `strtok_r()` elsewhere if you want nested calls to tokenizing routines. Or use `strcspn()` or `strpbrk()`. – Jonathan Leffler Sep 30 '17 at 20:12
  • OMG yes `matchingWords()` uses `strtok()`. At least now I know where to look for a fix; thanks – Aaron Parisi Sep 30 '17 at 20:14

0 Answers0