【问题标题】:Struggle with function strtok() in C在 C 中与函数 strtok() 斗争
【发布时间】:2016-02-07 17:09:57
【问题描述】:

我需要使用 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);

}

【问题讨论】:

  • 能显示“functionX”功能码吗?
  • @MohdShahril 是的。这是一个根据文件中写入的一些规则将每个标记与翻译相关联的功能。那是:pastebin.com/rBKi1Bx0
  • 请发布functionX 的最小版本,其中显示问题中的错误。添加评论链接是没有用的 - 当它是死链接时更是如此。
  • @WeatherVane 抱歉,我是新来的。
  • 你没有检查来自fopen的返回值。这样做是必不可少的。然后你没有关闭文件。

标签: c string strtok


【解决方案1】:

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

当您在functionX 中调用strtok 时,此信息会变得混乱,因为它会更改内部指针。然后,当您返回时,您正在使用这种错误状态。

您需要使用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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2020-09-18
    • 2018-05-23
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多