Originally Posted by
DaNxTh3xMaNx
So I found a sample program using strtok
Code:
character_pointer = strtok(inputline, " ");
while (character_pointer != NULL)
{
printf ("%s\n", character_pointer);
character_pointer = strtok(NULL, " ");
};
(note i changed the sample code to work in my program and this is the while loop that works for my program)
so this does get me the 3 separate parts but I really don't understand how it works. Can someone explain this while loop to me? also do I need a loop for my code since i know there will be three numbers always and separated by spaces always?
Okay, so strtok takes two arguments. The first is either a string - in which case it starts its "scanning" at the start of the specified string - or a null pointer, in which case it starts its scanning from where the previous call to strtok ended. The second argument is a string containing all the "delimiters" by which the string should be split up.
strtok works by returning a pointer to the first non-delimiter character it finds, having replaced the first delimiter AFTER this point with a null character, thereby creating a null-terminated string. If it doesn't find any such string, it returns a null pointer.
So, in your example, the first call to strtok returns a pointer to the first token (or "word"), separated by a space. Then (if the first call did not return a null pointer, which would imply that no tokens exist), it continues to loop through the string, pointing to (and printing) the next token each time, until eventually it fails to find a token.
You should note, also, that because of the way strtok changes delimiters into null pointers, it is destructive to the original string. So, in this case, the inputline string would now be terminated by the null character that strtok placed at the end of the first token.
You don't need a loop, but your alternative would be:
Code:
character_pointer = strtok(inputline, " ");
printf("%s", character_pointer);
character_pointer = strtok(NULL, " ");
printf("%s", character_pointer);
character_pointer = strtok(NULL, " ");
printf("%s", character_pointer);
So there's no real reason not to use a loop, since it's actually easier AND works for an arbitrary number of tokens.