Reputation: 25
Say I have a string called str of the format
"token1, token2, token3"
and I want to store each token into its own char array like so
char* tok1 = strtok(str, ", ");
char* tok2 = strtok(str, ", ");
char* tok3 = strtok(str, "\0"); //this line is incorrect
But I get an error on the third token because strtok() expects a non-null input. Since strtok() requires two parameters (a string and a delimiter), how would I retrieve that final token?
Upvotes: 0
Views: 560
Reputation: 57033
If you are parsing the same string, the value of the first parameter must be NULL
for all subsequent calls:
char* tok1 = strtok(str, ", ");
char* tok2 = strtok(NULL, ", ");
char* tok3 = strtok(NULL, "");
On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.
Upvotes: 5