与 C 中的函数 strtok() 斗争

Struggle with function strtok() in C

我需要使用 strtok 函数来分析一些字符串中的每个单词。 我写了这样的代码:

char *token;
token=strtok(string,symbol);
while(token!=NULL){
   functionX(token); //this is a function that anlayze the token
   token=strtok(NULL,symbol);
}

但 "functionX" 仅接收字符串的第一个单词和空指针。 如果我把

printf("%s",token);

它打印字符串的每一段,而不是 functionX。 我该如何解决?

这就是我所说的"functionX":

void match(char *token, char *code){
FILE *rules;
char *tmp_token;
char stream[15];
int found;
rules=fopen("rules.vk","r");
found=0;
while((fgets(stream,sizeof(stream),rules))>0){
    tmp_token=strtok(stream,";");
    if((strcmp(tmp_token,token))==0){
        strcpy(code,strtok(NULL,";"));
        found=1;
    }
}
if(found==0) strcpy(code,token);

}

这是使用strtok的难点之一。它在例程中有内部状态,跟踪最初传入的字符串中的位置(即第一个 strtok(string, symbol); 调用)。

当您在 functionX 中调用 strtok 时,此信息会变得混乱,因为它会更改内部指针。那么当你 return 你使用的是这个错误的状态。

您需要使用的是 strtok_r 例程,它保留了该指针的私有副本,您必须将其传递给对 strtok_r.

的调用

作为原始例程的示例,您可以将其更改为:

char *token;
char *save;
token=strtok_r(string,symbol, &save);
while(token!=NULL){
   functionX(token); //this is a function that anlayze the token
   token=strtok_r(NULL,symbol, &save);
}

并且内部例程可以更改为:

void match(char *token, char *code){
    FILE *rules;
    char *tmp_token;
    char *save;
    char stream[15];
    int found;
    rules=fopen("rules.vk","r");
    found=0;
    while((fgets(stream,sizeof(stream),rules))>0){
        tmp_token=strtok_r(stream,";", &save);
        if((strcmp(tmp_token,token))==0){
            strcpy(code,strtok_r(NULL,";", &save));
            found=1;
        }
    }
    if(found==0) strcpy(code,token);
}