Question

I used strtok() function with a while loop and it compiled, but ANYTHING after the while loop doesn't seem to exist for the compiler:

int main()
{
    int j = 1;
    char a[60] = "ion ana adonia doina doinn ddan ddao . some other words ";
    char *pch[36];
    pch[0] = strtok(a, ".");
    while (pch[j + 1] != NULL)
    {
        cout << pch[j - 1] << endl;
        pch[j] = strtok(NULL, ".");
        j++;
    }
    cout << "hello!"; //this doesnt display at all
        return 0;
}

I am using c-free.

Was it helpful?

Solution

Among other things, your while loop end condition is wrong. You're checking pch[j + 1] which is always uninitialized memory, causing the loop to continue unpredictably until you encounter a zero in memory which may cause the loop to stop.

On an alternate note, I highly discourage the use of strtok in C++, due to its string-destruction. Boost has a quite nice string parsing facility, and even in the base C++ language it's simple enough to do most parsing with built in string functionality.

OTHER TIPS

Your code is bizarre. Try this:

int main()
{
    int j = 0;
    char a[60] = "ion ana adonia doina doinn ddan ddao . some other words ";
    char *pch[36];
    pch[j] = strtok(a, ".");
    while (pch[j] != NULL)
    {
        cout << pch[j] << endl;
        pch[++j] = strtok(NULL, ".");
    }
    cout << "hello!"; //this doesnt display at all
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top