2012-11-21 4 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()을 사용 전에 제거 gets() 인해 잠재적 버퍼 오버런 결과 입력에 의하면, 경계 위험한 API이다

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

참고있다. 사용자 입력을 읽기위한 안전 메커니즘은 N 문자의 최대 수를 읽어 지정 %Ns 지정자 fgets() 또는 scanf() 것, 그리고 N는 null 종결 수 있도록 배열의 크기보다 하나 작아야합니다 :

scanf("%30s", userString); 

문자열이 파일에서 발견되면 break의 파일을 while에서 계속 검색하여 불필요한 처리를 피할 이유가 없습니다. iFound의 값은 checkWordInFile()에서 변경되지 않으며 반환 값으로 사용되지 않습니다. 0이 항상 반환됩니다. 루프 내에서 iFound = gC_FOUND;을 의미한다고 생각합니다. 발견 된 매크로와 찾지 못한 매크로를 정의했지만 함수 내에서 매크로를 사용하지는 않지만 하드 코딩 된 값을 사용합니다.

+0

안녕하세요 hmjd, 팁을 주셔서 감사와 동시에 나에게 수업을 가르쳐, 미래의 사용을 위해 유용 할 것입니다 :) –