int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
hey guys im hoping you can help me this is the sample code for using strtok it works fine. What im trying to do is modify it so that the user inputs the string to be split into words but i keep getting garbage any suggestions ?
FYI, your use of strtok() is incorrect and may very well stop working if you change compilers. You see, strtok() modifies the original string. In your case, your original string is a string literal allocated by the compiler for you. You should treat those as sacred, meaning you must not modify them in any way. Your compiler is forgiving, but others might not be as forgiving.
You need to make a copy of the string literal and then pass that copy to strtok().
As for getting the line from the user, Framework's suggestion is of course very good. But, it is also C++ and you are coding C. Any specific reason why you are coding C instead of C++?