2017-04-25 71 views
-2

下面的代碼片段有什麼問題;它在#25行失敗。我不明白爲什麼它失敗。儘管正確調用strtok失敗

#include <stdio.h> 
#include <string.h> 

char linebuf[1024]="SET SLMSRVR 10.133.2.102: 50011"; 
char *tempStr; 
char *str; 

int main() 
{ 
    tempStr = calloc(1024, sizeof(char)); 

    strcpy(tempStr, linebuf+strlen("SET SLMSRVR")); 
    printf("1 tempStr: %s\r\n", tempStr); 

    str = strtok(tempStr, ":"); 
    printf("2 tempStr: %s\tstr: %s\r\n", tempStr, str); 

    if (str != NULL){ 
     printf("Server IP: %s\r\n",str); 
    } else { 
     printf("Error 1\r\n"); 
    } 

    str = strtok(tempStr, NULL); 
    printf("3 tempStr: %s\tstr: %s\r\n", tempStr, str); 
    if (str != NULL) { 
     printf("Port: %s\r\n", str); 
    } 

    return 0; 
} 

這裏作爲的strtok的規範建議,首先它被稱爲與分隔符串,然後用NULL,在這兩種情況下的第一個參數的字符串進行解析。它第二次解析失敗。

有什麼想法?

+3

而且我們應該算線#25? –

回答

2

第二次你應該把它叫做str = strtok(NULL,「:」);

2

我相信你弄錯了。像

str = strtok(tempStr, NULL); 

呼叫沒有任何意義,你傳遞指針分隔字符串作爲NULL。如果您想繼續解析相同的字符串,則需要將第一個參數作爲NULL

引用C11,章§7.24.5.8,(重點煤礦

char *strtok(char * restrict s1, 

爲const char *限制S2);

呼叫到strtok()函數A序列打破了串指向s1爲標記,其中的每一個由一個字符從字符串指向 通過s2分隔的 序列。 序列中的第一個調用具有非空的第一個參數; 序列中的後續調用具有空的第一個參數。s2指向的分隔符字符串可能是 與呼叫呼叫不同。

也許你想要的是

str = strtok(NULL, ":"); //or some other delimiter 
+0

謝謝。是的,就拿到了。 – Abu

相關問題