CS50 Pset5 check()将太多单词视为错误拼写

时间:2018-08-03 03:25:22

标签: c trie cs50

我已将字典加载到树形结构中,并成功获得了speller.c,可使用以下load()和check()实现进行编译。

但是,当我运行该程序时,我的check()函数将不正确的单词数视为拼写错误。 (对于lalaland.txt,则是17756个单词中的17187个单词。)

我无法弄清楚我的代码出了什么问题,对于能帮助我指出正确方向的人,我将深表感谢。

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;

}

1 个答案:

答案 0 :(得分:0)

node *temp = root;

应该放在while循环中:

while (fscanf(dict, "%s", word) != EOF)

这样做,每次循环开始遍历文件中的新单词时,您都允许temp返回并指向根节点。