0

我希望我不会因此很快被否决,但我有一个正在为学校工作的项目,我必须在其中构建一个拼写检查器。我决定使用 trie,它似乎可以正常工作,但我有一个我找不到的错误。我认为问题在于以下,

bool load(const char* dictionary)
{

    if (!rootNode)
    {
        rootNode = trieNodeCreate();
        if (!rootNode)
        {
            printf("could not allocate root node");
            return false;
        }
    }

    // Open the file 
    FILE* fp = fopen(dictionary, "r");

    if (fp == NULL)
    {
        printf("could not open dictioanry %s\n", dictionary);
        return false;
    }


    int index = 0;
    for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
    {
        char word[LENGTH];
        if (c != '\n' )
        {
            word[index] = c;
            index++;
        }
        else
        {
            trieWordInsert(word, rootNode);
            index = 0;
                wordCount ++;

        } 

    }
    fclose(fp);

    if (wordCount)
    {
        return true;
    }
    return false;
}

但我一直找不到它。该项目的其余部分可以在

https://github.com/iMillJoe/spell-checker

4

2 回答 2

2

在循环之外声明你的word[LENGTH]数组,否则它只会丢弃word指针并在每个循环结束时释放分配的,创建一个新的。我不认为你想要那个,我认为你宁愿只在if条件没有得到满足时才想要那个。

我可能不知道是什么trieWordInsert,但我会假设你需要一个0终结者。

  • word[LENGTH] = { 0 };在之前声明for( ... ) { ... }
  • 在那里的块memset( word, 0, LENGTH);内添加一个else
  • 包括memory.hstring.h如果memset您到目前为止还没有包括其中任何一个

这应该是它,我想......

编辑:在了解了如何推动trieWordInsert或多或少的问题之后......word

EZ 模式的直接代码:

bool load( const char* dictionary )
{

    if ( !rootNode )
    {
        rootNode = trieNodeCreate( );
        if ( !rootNode )
        {
            printf( "could not allocate root node" );
            return false;
        }
    }

    // Open the file 
    FILE* fp = fopen( dictionary, "r" );

    if ( fp == NULL )
    {
        printf( "could not open dictioanry %s\n", dictionary );
        return false;
    }

    int index = 0;
    char word[LENGTH];
    for ( int c = fgetc( fp ); c != EOF; c = fgetc( fp ) )
    {
        if ( c != '\n' )
        {
            word[index] = c;
            index++;
        }
        else
        {
            word[index] = 0;
            trieWordInsert( word, rootNode );
            index = 0;
            wordCount++;
        }

    }
    fclose( fp );

    if ( wordCount )
    {
        return true;
    }
    return false;
}
于 2014-03-09T18:41:01.800 回答
1

我认为您没有以 '\0' 结尾

char word[LENGTH];
 if (c != '\n' )
 {
     word[index] = c;
     index++;
 }
 else
 {
     word[index] = '\0'; //missing this one!!!
     trieWordInsert(word, rootNode);
     index = 0;
     wordCount ++;
 } 

我认为您最好fscanf逐字逐句地使用和阅读文件。

于 2014-03-09T18:44:57.833 回答