int main () {
char *results = NULL;
char line[] = "a,b,c";
const char delim[] = ",";
// First token
results = strtok(line, delim);
if (strcmp(results, "a") == 0)
{ OtherFunction(line); }
}
void OtherFunction(char* line)
{
results = strtok(line, delim);
// Read through
while(results != NULL )
{
printf(" %s\n", results);
results = strtok(NULL, delim);
}
}
Why I am not getting the b and c in the other function but if I do the same thing in the original it works?
strtok()
is a horrible abomination. It's not thread-safe, re-entrant or any of the good things, it keeps state (it remembers where it last read from) and it modifies the string it operates on !
strtok()
replaces the delimiters you specify with '\\0'
in the string. When you call strtok(line, delim)
the second time (in OtherFunction()
), the string is already null-terminated after the a
.
Also, using strtok()
on a string literal is not allowed because of the change it causes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.