2010-01-22 54 views
1

strcmp,當餵食strtok的結果時,在下面的代碼中似乎是對我公然謊言。幫助! strcmp在餵食strtok時給我說謊結果

int fSize; 
char * buffer=NULL; 
char * jobToken = "job"; 
char * nextToken=NULL; 
job * curJob=NULL; 
struct node * head=NULL; 
struct node * parseList(FILE* file){ 
    fseek(file,0,SEEK_END); 
    fSize=ftell(file); 
    buffer = (char*)malloc(fSize+1); 
    printf("%d chars: reading buffer now:\n",fSize); 
    fseek(file,0,SEEK_SET); 
    fread (buffer,1,fSize,file); 
    nextToken = strtok(buffer, " \n"); 
    while (nextToken!=NULL){ 
      printf("**Running Token: %s**\n",nextToken); 
      if (strcmp(nextToken,jobToken)){ 
        printf("Accepted %s as %s\n",nextToken,jobToken);     
      }else{ 
        printf("not %s, %s\n",jobToken,nextToken); 
      } 

      printf("End of state - %s\n",nextToken); 

      nextToken = strtok(NULL, " \n"); 
    } 
    free (buffer); 
    return NULL; 
} 

隨着在parseList參數此輸入一個文件:

job 23 
job 10 

給出了這樣的輸出:

14 chars: reading buffer now: 
**Running Token: job** 
not job, job 
End of state - job 
**Running Token: 23** 
Accepted 23 as job 
End of state - 23 
**Running Token: job** 
not job, job 
End of state - job 
**Running Token: 10** 
Accepted 10 as job 
End of state - 10 

所在!

回答

6

strcmp當你比較的字符串相等時返回0。您需要使用if (!strcmp(...))

+0

Raaaage!謝謝,現在看起來很明顯。 – mjames 2010-01-22 01:31:20

+1

我寧願明確地比較0;它減少了將結果解釋爲布爾值的機會。我用'access'完成同樣的事情,而其他的零都意味着成功。 – 2010-01-22 01:36:51

+0

我喜歡'#define streq(s1,s2)(strcmp((s1),(s2))== 0)',因爲它將語義想法放入名稱 – 2012-11-27 12:44:42

1

不相關的問題,但幾個百分點:

  • fread()後,您應該設置buffer[fSize] = 0;,否則就不是一個字符串。
  • 使用fseek(file,0,SEEK_END);isn't guaranteed to work確定要在文本文件或二進制文件中讀取的字符數。

就個人而言,我會寫malloc()電話爲:

buffer = malloc(fSize+1); 

,因爲這會警告我,如果我忘了#include <stdlib.h>,並且更容易閱讀。 C中不需要演員陣容。