for Speller in Pset 5, I am having issues with my check function, not sure how to deal with words with apostrophe and need some tips if possible. The issue should be with the check function of my code, when comparing with keys I loaded the same number of words for the dictionary. However, when using check50, it said that my code has issues with basic words but I cant seem to reproduce them when I use a text file of my own. Below is my code for check as well as hash.
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26;
// Hash table
node *table[N];
int counter = 0;
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
//if apostrophe...
int hcode = hash(word);
node *trav = table[hcode];
// set to start of hash table
while (trav!=NULL)
{
if (strcasecmp(word,trav->word)==0)
{
return true;
}
trav = trav->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{ int first = 0;
// TODO: Improve this hash function
// return 0-25 according to first letter of the word
char lower = tolower(word[0]);
first = lower - 97;
return first;
}
// Loads dictionary into memory, returning true if successful, else false string input represents dictionary file name
bool load(const char *dictionary)
{
FILE *dict = fopen(dictionary, "r");
char tmpword[LENGTH +1];
//allocate space for the words
int hcode;
while (fscanf(dict, "%s", tmpword)!=EOF)
{
node *n = malloc(sizeof(node));
//after 2 words in dictionaries small, cant end fscanf returns 0 value
strcpy(n->word, tmpword);
hcode=hash(tmpword);
n->next = table[hcode];
table[hcode]=n;
counter++;
}
fclose(dict);
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size()
{
return counter;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
// TODO
//go through each path
for (int i =0; i<N;i++)
{
node *cursor =table[i];
node *tmp = table[i];
while (cursor->next!=NULL)
{
cursor = cursor->next;
free(tmp);
tmp = cursor;
}
free(cursor);
}
//check if all unloaded
return true;
}