strtok小陷阱(C语言编程)
strtok的接口如下:
char *strtok(char *s, const char *delim);
相关描述:
DESCRIPTION
A ‘token’ is a nonempty string of characters not occurring in the string delim, followed by \0 or by a character occurring in delim.
The strtok() function can be used to parse the string s into tokens. The first call to strtok() should have s as its first argument. Subsequent calls should have the first
argument set to NULL. Each call returns a pointer to the next token, or NULL when no more tokens are found.
If a token ends with a delimiter, this delimiting character is overwritten with a \0 and a pointer to the next character is saved for the next call to strtok(). The delim-
iter string delim may be different for each call.
The strtok_r() function is a reentrant version of the strtok() function, which instead of using its own static buffer, requires a pointer to a user allocated char*. This
pointer, the ptrptr parameter, must be the same while parsing the same string.
于是想着按如下方式使用:
#include <stdlib.h>
#include <string.h>
char names[100] = “abc|def|asc”;
const char *tokens = “|”;
int main(int argc, char **argv)
{
char *p_name = strtok(names, tokens);
while (NULL != p_name) {
printf(”%s\n”, p_name);
p_name = strtok(g_app_names, tokens);
}
return 0;
}
结果出错了,程序进入了死循环,什么原因呢?仔细看了一下接口描述,有这么一句:
The first call to strtok() should have s as its first argument. Subsequent calls should have the first argument set to NULL. Each call returns a pointer to the next token, or NULL when no more tokens are found.
原来只是第一次strtok转入原串,第二次之后,就使NULL就可以了,要不就进入死循环了。
#include <stdlib.h>
#include <string.h>
char names[100] = “abc|def|asc”;
const char *tokens = “|”;
int main(int argc, char **argv)
{
char *p_name = strtok(names, tokens);
while (NULL != p_name) {
printf(”%s\n”, p_name);
p_name = strtok(NULL, tokens);
}
return 0;
}
再运行一下吧:
abc
def
asc
正确了:)
多谢
张久安
If you enjoyed this post, make sure you subscribe to my RSS feed!









No Comments, Comment or Ping
Reply to “strtok小陷阱(C语言编程)”
You must be logged in to post a comment.