【问题标题】:CS50 Pset5 check() counting too many words as misspelledCS50 Pset5 check() 将太多单词计数为拼写错误
【发布时间】:2018-08-03 03:25:21
【问题描述】:

我已将字典加载到树结构中,并成功获得了 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;

}

【问题讨论】:

  • node *temp = root; 似乎属于while (fscanf(dict, "%s", word) != EOF) 内部,而不是在它之前。
  • @chux 非常感谢!这正是问题所在。我的代码现在可以正常工作了。
  • 名称:LENGTH 未在发布的代码中的任何位置定义
  • 发布的代码缺少所需的#include 语句,因此无法编译!您是否希望我们猜测您包含了哪些头文件?

标签: c trie cs50


【解决方案1】:
node *temp = root;

应该放在这个while循环里面:

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

通过这样做,您允许 temp 在每次循环开始迭代文件中的新单词时返回并指向根节点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多