2012-11-21 93 views
1

我有下面的這段代碼來檢查輸入與普通單詞字典,並檢查輸入是否匹配存儲在passHistory文件中的先前輸入。我的問題是,strcmp方法比較C中的字符串在我的代碼中似乎沒有正確執行,因爲如果在passHistory中已經使用了常用單詞或輸入,它將無法顯示相應的錯誤。C輸入檢查和以前的輸出驗證代碼

一些指導將不勝感激。

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

#define MAX 30 
#define gC_FOUND 99 
#define gC_NOT_FOUND -99 


int checkWordInFile(char * fileName,char * theWord); 



int main() 
{ 

    char userString[MAX + 1]; 

    int iResult; 

    printf("Enter your string: "); 
    gets(userString); 


    printf("\n\nYou entered: %s, please wait, checking in dictionary.\n\n", userString); 
    iResult = checkWordInFile("dictionary.txt",userString); 




    if(iResult == gC_FOUND) 
    { 
     printf("\nFound your word in the dictionary"); 
    } 
    else 
    { 
     printf("\nCould not find your word in the dictionary"); 
    } 

    iResult = checkWordInFile("passHistory.txt",userString); 
    if(iResult == gC_FOUND) 
    { 
     printf("\nPassword used"); 
    } 
    else 
    { 
     printf("\nOk to use!"); 
    } 

    printf("\n\n\n"); 
    system("pause"); 

} /* end of main */ 

int checkWordInFile(char * fileName,char * theWord){ 

    FILE * fptr; 
    char fileString[MAX + 1]; 
    int iFound = -99; 
    //open the file 
    fptr = fopen(fileName, "r"); 
    if (fptr == NULL) 
    { 
     printf("\nNo dictionary file\n"); 
     printf("\n\n\n"); 
     system("pause"); 
     return (0); // just exit the program 
    } 

    /* read the contents of the file */ 
    while(fgets(fileString, MAX, fptr)) 
    { 
     if(0 == strcmp(theWord, fileString)) 
     { 
      iFound = -99; 
     } 
    } 

    fclose(fptr); 

    return(0); 



}//end of checkwORDiNFile 
+0

你怎麼知道'strcmp'方法工作不正常? – PearsonArtPhoto

回答

3

fgets()將新行字符(如果遇到)寫入到正在填充的緩衝區中。使用strcmp()之前移除:

char* new_line = strrchr(fileString, '\n'); 
if (new_line) *new_line = 0; 

注意gets()是一種危險的API由於無邊界檢查該輸入,潛在地導致緩衝區溢出。用於讀取所述用戶輸入一個更安全的機制將是fgets()scanf()%Ns specifier其中N指定要讀取的字符的最大數目,並且N必須比陣列的尺寸少一個,以允許空終止:

scanf("%30s", userString); 

在文件中找到字符串時,沒有理由繼續從while搜索文件的其餘部分break以避免不必要的處理。請注意,iFound的值在checkWordInFile()內永遠不會更改,並且不會用作返回值:總是返回0。我想你的意思是在循環內iFound = gC_FOUND;。您還定義了宏以指示找到並未找到,但不要在函數中使用這些宏,而是使用硬編碼的值。

+0

嗨hmjd,謝謝你的提示,同時教我一節課,將來會用到:) –