I am working on a project which involves using strtok
and for some reason I am getting null values instead of the actual values (which should be "Two" and "Three"). Here is my code:
int main(){
int h,z;
char text[100] = "One Two Three";
for(h = 0; h < 4; h ++){
char *first = strtok(text, " ");
printf("%s\n",first);
for(z = 0; z < 3; z++){
char *second = strtok(NULL, " ");
printf("%s\n",second);
}
}
return 0;
}
The output I am getting is:
One
Two
Three
One
(null)
(null)
One
(null)
(null)
One
(null)
(null)
What can I do in order to get the right value Two
and Three
instead of null?
Note that your code actually re-tokenizes the string text
4 times, as you have nested loops. Note also that z < 3
is one off and should be z < 2
:
int main(){
int h,z;
char text[100] = "One Two Three";
for(h = 0; h < 4; h ++){
char *first = strtok(text, " ");
printf("%s\n",first);
for(z = 0; z < 2; z++){
char *second = strtok(NULL, " ");
printf("%s\n",second);
}
}
return 0;
}
But strtok
introduces '\0'
-characters each time a token is found. Hence, after the first run of the for(h...)
-loop, text
will be "One"
, and for any subsequent loops only one token can be found; tokens #2 and #3 do not exist in "One"
.
To re-tokenize (for whatever reason), you'll have to re-initialize text
:
int main(){
int h,z;
char text[100];
for(h = 0; h < 4; h ++){
strcpy(text,"One Two Three");
char *first = strtok(text, " ");
printf("%s\n",first);
for(z = 0; z < 2; z++){
char *second = strtok(NULL, " ");
printf("%s\n",second);
}
}
return 0;
}