2015-01-16 72 views
1

我在比較文件中的字符串時遇到了問題。 我想從一個字典文件中創建一個單詞列表。我不知道爲什麼strcmp()只會返回-1或1,即使我使用我的文件中的單詞。在輸出我有比如:1somethingsomething代替0somethingsomething來自stdin的strcmp()字符串和來自文件的字符串

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


struct words 
{ 
    char *word; 
    struct words *next; 
}; 

void pushBack(struct words **headPointer, char string[]) 
{ 
    struct words *pointer; 
    pointer = *headPointer; 
    if (*headPointer == NULL) 
    { 

     *headPointer = (struct words*)malloc(sizeof(struct words)); 
     (*headPointer)->next = NULL; 
     (*headPointer)->word = (char*)malloc(sizeof(char)*(strlen(string)+1)); 
     strcpy((*headPointer)->word, string); 

    } 
    else 
    { 
     while (pointer->next != NULL) 
     { 
      pointer = pointer->next; 
     } 
     pointer->next = (struct words*)malloc(sizeof(struct words)); 
     pointer = pointer->next; 
     pointer->next = NULL; 
     pointer->word = (char*)malloc(sizeof(char)*(strlen(string)+1)); 
     strcpy(pointer->word, string); 
    } 
} 

void createList(struct words **headPointer) 
{ 
    FILE *fp; 
    char string[80]; 

    if ((fp = fopen("polski.txt", "rw")) == NULL) 
    { 
     printf ("Nie mogê otworzyæ pliku test.txt do zapisu!\n"); 
     exit(-1); 
    } 
    else 
    { 
     while(fgets(string, 80, fp) != NULL) 
     { 
      pushBack(headPointer, string); 
     } 
    } 
} 

int seek(struct words *head, struct words **wordBeforePointer, struct words **wordAfterPointer) 
{ 
    char string[80]; 

    printf("Type a word to seek:\n"); 
    scanf("%s", string); 

    *wordBeforePointer = NULL; 
    *wordAfterPointer = NULL; 

    if (head != NULL) 
    { 
     if (strcmp(head->word, string) == 0) 
     { 
      return 1; 
     } 
     while(head->next != NULL) 
     { 
      head = head->next; 
      printf("%s", string); 
      printf("%s", head->word); 
      printf("%d", strcmp(head->word, string)); 
      if (strcmp(head->word, string) == 0) 
      { 
       return 1; 
      } 
     } 
    } 
    return 0; 
} 

int main() 
{ 
    struct words *head, *wordBefore, *wordAfter; 
    head = NULL; 
    wordBefore = NULL; 
    wordAfter = NULL; 


    createList(&head); 
    printf("%d", seek(head, &wordBefore, &wordAfter)); 


    return 0; 
} 
+0

可能是終止字符 – theadnangondal

+0

請記住'strcmp'區分大小寫。 –

回答

3

fgets電話不實際刪除尾隨的換行符,所以採用這種方法的人常常發現,strcmp不工作,只是因爲:

"thisword\n" != "thisword" 

如果你想手動去除它,你可以使用類似於:

while (fgets (inputLine, 80, filePtr) != NULL) { 
    // Get size of input line. 

    size_t strSize = strlen (inputLine); 

    // If there's a newline at the end, remove it. 

    if ((strSize > 0) && (inputLine[strSize-1] == '\n')) 
     inputLine[strSize-1] = '\0'; 

    // Do whatever you need to "non-newline" line. 

    doSomethingWith (inputLine); 
} 
+0

它的工作原理! :) 非常感謝 –