When my function is_ingredient_list
passes a pointer to another function is_ingredient
, which copies the content into another array and tokenizes it, my original pointer gets affected and stops tokenizing after the first token. How to fix this problem?
#include <stdio.h>
#include <string.h>
int is_ingredient(const char* str){
char tmp[1024];
strncpy(tmp, str, sizeof(tmp));
tmp[sizeof(tmp)-1] = '\0';
char delim[] = " ";
char *token = strtok(tmp, delim); // this line causes the problem
//printf("%s\n", str);
return 1;
}
int is_ingredient_list(const char* str){
char tmp[1024];
char delim[] =",";
strncpy(tmp, str, sizeof(tmp));
tmp[sizeof(tmp)-1]='\0';
char* token = strtok(tmp, delim);
while(token!=NULL){
if(is_ingredient(token)==0) return 0;
printf("%s\n", token);
token = strtok(NULL, delim);
}
return 1;
}
The strtok
function uses static internal data to keep track of where it's at when parsing a string. If you parse a string in a loop, then inside of the loop parse another string with strtok
as you're doing, you're resetting that internal buffer so that subsequent calls that attempt to parse the "outer" string won't work as expected.
Instead, use strtok_r
(or strtok_s
on Windows) which takes an additional parameter to save its state.
int is_ingredient(const char* str){
char tmp[1024];
char *ptr = NULL;
strncpy(tmp, str, sizeof(tmp));
tmp[sizeof(tmp)-1] = '\0';
char delim[] = " ";
char *token = strtok_r(tmp, delim, &ptr);
//printf("%s\n", str);
return 1;
}
int is_ingredient_list(const char* str){
char tmp[1024];
char *ptr = NULL;
char delim[] =",";
strncpy(tmp, str, sizeof(tmp));
tmp[sizeof(tmp)-1]='\0';
char* token = strtok_r(tmp, delim, &ptr);
while(token!=NULL){
if(is_ingredient(token)==0) return 0;
printf("%s\n", token);
token = strtok_r(NULL, delim, &ptr);
}
return 1;
}