Pointer Woe

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 ?
These probably should be posted in teh Beginners section, but it's no beg deal.

You need to read your user input into str and then use strtok as you are now.
closed account (zb0S216C)
Calling the member getline( ) of cin will allow the user to input a string with spaces[1].

References:
[1]http://www.cplusplus.com/reference/iostream/istream/getline/

Wazzak
Last edited on
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++?
Topic archived. No new replies allowed.