gpt4 book ai didi

c - 为什么我的数组采用先前的array [index]值并进行检查?

转载 作者:行者123 更新时间:2023-11-30 19:24:41 25 4
gpt4 key购买 nike

我正在写一个拼写检查器,但是我遇到一个问题,如果先前的数组长度大于当前正在检查的数组长度,由于某种原因,它会添加先前数组中的“缺少”字符。

例如,要检查的单词是“ cat”,而之前的单词是“ bear”,那么它将循环通过的单词是“ catr”。我使用了调试器工具,一切看起来都还不错。用c [len]初始化数组似乎不起作用。

加载方法:

bool load(const char *dictionary)
{
// Open dictionary list
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}

// Create a universal root node to be used to traverse through the trie
root = malloc(sizeof(node));
node *pointer = root;

int index, charCounter = 0;
char c;

// Insert words into trie
while (1)
{
// Open the file and get a new char
c = fgetc(file);
//printf("%c", c);

if (c == '\'')
{
index = N - 1;
}
else
{
index = c - case;
}

if(isalpha(c) || c == '\'')
{
if(pointer->children[index] == NULL)
{
// Allocate memory for new node
pointer->children[index] = malloc(sizeof(node));
// Set the pointer equal to that new node
pointer = pointer->children[index];
}
else
{
pointer = pointer->children[index];
}
}
else
{
pointer->isWord = true;
pointer = root;
numWords++;
}

// If end of the file, close it and stop the loop
if(feof(file))
{
fclose(file);
break;
}
charCounter++;
//printf("%i", charCounter);
}

// Indicate success
return true;
}


检查方法:

bool check(const char *word)
{
// Set the pointer to equal the root with every new word
node *pointer = root;

// Create array to traverse through
int len = strlen(word);
int index = 0;
char c[len];

// Create a word array with all letters lowercase
for (int i = 0; i<len; i++)
{
if (isupper(word[i]))
{
c[i] = tolower(word[i]);
}
else
{
c[i] = word[i];
}
}


// Loop to go through the every letter in the word
for (int i = 0; i<=len; i++)
{
// Index would equal the position in the node
index = c[i] - case;
//printf("%i", index);

if (c[i] == '\'')
{
index = N - 1;
}

if (c[i] != '\0')
{
// Checking basics for the location if NULL then automatically not in node so false
if (pointer->children[index] == NULL)
{
return false;
}
// Otherwise, if it's not NULL it has to be a valid entry in the node
else
{
pointer = pointer->children[index];
}
}
else
{
if (pointer->isWord == true)
{
return true;
}
}
}
return false;
}

最佳答案

我不想给你代码,但是在添加和检查下一个字符是否是单词的结尾时很重要,因为一旦移动了指针,就无法返回检查isWord。

您可以将'c'读入缓冲区,或存储指向当前节点的指针,然后再将指针移至'.children [i]'以在到达'\ 0'时检查isWord。

希望能有所帮助。

关于c - 为什么我的数组采用先前的array [index]值并进行检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60046339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com