2016-02-07 38 views
-1

我需要使用strtok函數來分析某些字符串中的每個單詞。 我寫了這樣的代碼:在函數strtok()中奮鬥C

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); 

}

+10

可以顯示「functionX」功能碼? –

+0

@MohdShahril Yup。 這是一個根據文件中寫入的一些規則將每個標記與翻譯關聯的函數。 即: pastebin.com/rBKi1Bx0 – NosPix

+0

請發佈最小版本的'functionX',它在問題*中顯示錯誤*。添加評論鏈接是沒有用的 - 當它是無效鏈接時更是如此。 –

回答

2

這是在使用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); 
}