strtok
modifies the input array by overwriting the delimiters with 0s; it's not that everything after the first token has been removed or cleared, it's just that you have a string terminator following the first token, so nothing after it gets printed.
For example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main( void )
{
char str[] = "This is a test";
printf( "before strtok: " );
for ( size_t i = 0; i < sizeof str; i++ )
{
if ( isprint( str[i] ) )
putchar( str[i] );
else
putchar( '.' );
}
putchar ( '\n' );
char *token = strtok( str, " " );
while ( token )
{
printf( "token = %8s, str = ", token );
for ( size_t i = 0; i < sizeof str; i++ )
{
if ( isprint( str[i] ) )
putchar( str[i] );
else
putchar( '.' );
}
putchar( '\n' );
token = strtok( NULL, " " );
}
printf( "after all strtok: " );
for ( size_t i = 0; i < sizeof str; i++ )
{
if ( isprint( str[i] ) )
putchar( str[i] );
else
putchar( '.' );
}
putchar( '\n' );
return 0;
}
Here's the output (a .
represents a 0 in this case):
before strtok: This is a test.
token = This, str = This.is a test.
token = is, str = This.is.a test.
token = a, str = This.is.a.test.
token = test, str = This.is.a.test.
after all strtok: This.is.a.test.
After the strtok
calls, all the other tokens are still there, but because we've overwritten the blank spaces with 0s, all the regular text processing routines (strcpy
, strcat
, printf
, puts
, etc.) only see the first token.
If you want to preserve the contents of the original string, you will have to copy them into another buffer and perform the strtok
calls on that buffer.