所以我strtok用来分割一个char数组" "。然后,将拆分的每个单词放入一个函数,该函数将基于列表确定单词的值。但是,我将函数调用放置在while循环中间的所有步骤,以拆分char停止的数组。
我是否必须拆分数组,将其存储在另一个数组中,然后遍历第二个数组?
p = strtok(temp, " ");
while (p != NULL) {
value = get_score(score, scoresize, p);
points = points + value;
p = strtok(NULL, " ");
}
Run Code Online (Sandbox Code Playgroud)
因此,只要value = get_score(score, scoresize, p);有while第一个单词之后的循环就会中断。
strtok()使用隐藏状态变量来跟踪源字符串的位置。如果您strtok直接或间接在中再次使用get_score(),则此隐藏状态将更改为使调用p = strtok(NULL, " ");无意义。
不要使用strtok()这种方式,请使用许多系统上可用的strtok_r POSIX中标准化的改进版本。或使用strspn和重新实现它strcspn:
#include <string.h>
char *my_strtok_r(char *s, char *delim, char **context) {
char *token = NULL;
if (s == NULL)
s = *context;
/* skip initial delimiters */
s += strspn(s, delim);
if (*s != '\0') {
/* we have a token */
token = s;
/* skip the token */
s += strcspn(s, delim);
if (*s != '\0') {
/* cut the string to terminate the token */
*s++ = '\0';
}
}
*context = s;
return token;
}
...
char *state;
p = my_strtok_r(temp, " ", &state);
while (p != NULL) {
value = get_score(score, scoresize, p);
points = points + value;
p = my_strtok_r(NULL, " ", &state);
}
Run Code Online (Sandbox Code Playgroud)