Reputation: 6227
I have this following piece of code to check an input against a dictionary of common words and also check if input matches previous input stored in the passHistory file.My problem is that the strcmp method to compare strings in C doesn't seem to execute correctly in my code as it fails to show appropriate error if common word used or input was already used in passHistory.
Some guidance would be appreciated.
#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
Upvotes: 1
Views: 298
Reputation: 122001
fgets()
writes the new-line character, if encountered, into the buffer it is populating. Remove it before using strcmp()
:
char* new_line = strrchr(fileString, '\n');
if (new_line) *new_line = 0;
Note that gets()
is a dangerous api due to no bounds checking on the input, potentially resulting in a buffer overrun. A safer mechanism for reading the user input would be fgets()
or scanf()
with the %Ns
specifier where N
specifies the maximum number of characters to read, and N
must be one less than the size of the array to allow for the null terminator:
scanf("%30s", userString);
When the string is found in the file there is no reason to keep searching the remainder of the file, break
from the while
to avoid unnecessary processing. Note that iFound
s value never changes within the checkWordInFile()
and is not used as the return value: 0
is always returned. I think you meant iFound = gC_FOUND;
within the loop. You have also defined macros to indicate found and not found but do not use these within the function, but use the hard-coded values.
Upvotes: 3