【发布时间】:2013-12-08 20:34:30
【问题描述】:
我正在编写一个程序来按照翻译路径翻译给定的单词。 给定单词的每个字母代表一个特定的节点。
输出应该是所有要翻译的单词,然后是相应的翻译,但我收到的是输出而不是:
a: 4��t� xp� t����
an: 4��t� xp� t����
ant: 4��t� xp� t����
at: 4��t� xp� t����
atom: 4��t� xp� t����
no: 4��s� xp� t����
not: 4��s� xp� t����
tea: 4��q� xp� t����
ten: 4��q� xp� t����
main.c:
int main()
{
struct Trie* trie = trie_alloc();
trie_insert_from_file(trie, "dictionary.txt");
trie_print_mappings(trie);
trie_free(trie);
return 0;
}
trie.c:
int trie_insert(Trie* trie, const char* key, const char* value)
{
...
}
void trie_insert_from_file(Trie* trie, const char* file_name)
{
FILE* file = fopen(file_name, "r");
if (file == NULL)
{
fprintf(stderr, "Unable to open %s for reading: %s\n",
file_name, strerror(errno));
return;
}
while (!feof(file))
{
char key[64];
char value[64];
int nb_matched = fscanf(file, "%63[a-z] : %63[a-z]\n", key, value);
if (nb_matched == 2)
{
trie_insert(trie, key, value);
}
else
{
fprintf(stderr, "Syntax error while reading file\n");
fclose(file);
return;
}
}
fclose(file);
}
static char* str_append_char(const char* str, char c)
{
size_t len = strlen(str);
char* new_str = malloc(len + 2);
strcpy(new_str, str);
new_str[len] = c;
new_str[len + 1] = '\0';
return new_str;
}
static void trie_print_mappings_aux(Trie* trie, const char* current_prefix)
{
if (trie->value != NULL)
printf("%s: %s\n", current_prefix, trie->value);
int i;
for (i = 0; i < TRIE_NB_CHILDREN; i++)
{
Trie* child = trie->children[i];
if (child != NULL)
{
char* child_prefix =
str_append_char(current_prefix, trie_get_child_char(i));
trie_print_mappings_aux(child, child_prefix);
free(child_prefix);
}
}
}
void trie_print_mappings(Trie* trie)
{
trie_print_mappings_aux(trie, "");
}
trie.h:
#define TRIE_NB_CHILDREN 26
typedef struct Trie
{
char* value;
struct Trie* children[TRIE_NB_CHILDREN];
} Trie;
当我使用函数 trie_insert 手动插入数据而不使用 insert_from_file 读取 .txt 文件时,不会发生这种情况。
Eg. trie_insert(trie, (const char*)&"ten", (const char*)&"tien");
trie_insert(trie, (const char*)&"no", (const char*)&"nee");
trie_insert(trie, (const char*)&"not", (const char*)&"niet" );
...
经过一些研究,我认为这可能与我正在超出允许的内存位置进行写入有关。但我不知道到底哪里出了问题。
insert_from_file、str_append_char、trie_print_mapping_aux* 函数应该可以正常工作,因为它们是给我的。所以错误可能在我实现的 trie_insert 中。
任何帮助将不胜感激。
【问题讨论】:
-
哇!请缩短代码 e.
-
除了厨房水槽和两个(最有可能的)相关功能
trie_insert_from_file和trie_print_mappings之外的所有东西......是的,我们确实需要看看你怎么样设置它们。 -
文件的字符代码("dictionary.txt") 不是 ASCII 码?
-
"dictionnary.txt" 包含全字母,没有ASCII码