I have loaded the dictionary into a tree structure and successfully gotten speller.c to compile with the following implementations of load() and check().
However, when I run the program, an incorrect number of words are counted as misspelled by my check() function. (In the case of lalaland.txt, it's 17187 words out of 17756).
I can't figure out what's wrong with my code and would be extremely grateful to anyone who could help point me in the right direction.
typedef struct node
{
bool isword;
struct node *children[27];
}
node;
node *root = NULL;
// Function returns the position of any given letter in the alphabet e.g. a = 1, b = 2 etc. Returns 0 for an apostrophe.
int index(char letter)
{
if (isalpha(letter))
{
int i = letter - 96;
return i;
}
return 0;
}
// Keeps track of number of words loaded into dictionary.
unsigned int wordno = 0;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
char newword[LENGTH + 1];
node *temp = root;
for (int j = 0; j < strlen(word); j++)
{
//Makes each letter of the input lowercase and inserts it into a new array.
newword[j] = tolower(word[j]);
}
for (int i = 0; i < strlen(word); i++)
{
//Finds the position of the character in the alphabet by making a call to index().
int letter = index(newword[i]);
if (temp->children[letter] == NULL)
{
return false;
}
else
{
temp = temp->children[letter];
}
}
if (temp->isword == true)
{
return true;
}
return false;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
FILE *dict = fopen(dictionary, "r");
root = calloc(1, sizeof(node));
node *temp = root;
if (dict == NULL)
{
fprintf(stderr, "Could not load dictionary.\n");
return false;
}
char word[LENGTH+1];
while (fscanf(dict, "%s", word) != EOF)
{
for (int i = 0; i < strlen(word); i++)
{
int letter = index(word[i]);
if (temp->children[letter] == NULL)
{
temp->children[letter] = calloc(1, sizeof(node));
if ((temp->children[letter]) == NULL)
{
unload();
return false;
}
}
temp = temp->children[letter];
}
temp->isword = true;
wordno++;
}
return true;
}
node *temp = root;
should be placed inside this while loop:
while (fscanf(dict, "%s", word) != EOF)
By doing this, you allow temp to go back and point to the root node each time the loop begins iterating over a new word in the file.