首页 > 解决方案 > 在 c 中的拼写程序中实现多个函数会返回所有拼写错误的单词。在 cs50 pset5 拼写器中

问题描述

该代码实现了这些功能:

问题是该函数load()仅将文件字典中的第一个单词加载到哈希表中。

这是故障功能

// Represents a node in a hash table. length being the largest word in the dictionary
typedef struct node {
    char word[LENGTH + 1];
    struct node *next;
} node;

// Number of hashes in hash table represent the alphabet
const unsigned int N = 26;
// a count variable to pass to the size function
int count = 0;

// Hash table
node *table[N];

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary) {
    int b = 0;
    char *c = malloc((LENGTH + 1) * sizeof(char));
    FILE *f = fopen(dictionary, "r");
    while (fscanf(f, "%s", c) != EOF) {
        // b is the hash number 
        b = hash(c);
        if (table[b] == NULL) {
            node *n = malloc(sizeof(node));
            if (n == NULL) {
                return false;
            }
            strcpy(n->word, c);
            n->next = NULL;

            table[b] = n;
            count++;
            return true;
        } else
        if (table[b] != NULL) {
            node *n = malloc(sizeof(node));
            if (n == NULL) {
                return false;
            }

            strcpy(n->word, c);
            n->next = table[b];
            table[b] = n;
            count++;
            return true;
        }
    }
    return false;
}

标签: ccs50

解决方案


问题是函数总是true在将第一个单词插入哈希表后返回。在其他问题中,您忘记了 freec和 close f

这是修改后的版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

node *table[N];
int count;

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary) {
    char buf[LENGTH + 1];
    FILE *f = fopen(dictionary, "r");
    if (f == NULL)
        return false;

    // problem: how to prevent `fscanf` from storing too many characters to buf?
    while (fscanf(f, "%s", buf) == 1) {
        node *n = malloc(sizeof(node));
        if (n == NULL) {
            fclose(f);
            return false;
        }
        strcpy(n->word, buf);
        // b is the hash number 
        int b = hash(buf);
        n->next = table[n];
        table[b] = n;
        count++;
    }
    fclose(f);
    return true;
}

推荐阅读