C语言英汉词典源码
时间: 2023-07-05 22:20:48 浏览: 287
以下是一个简单的C语言英汉词典的源码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASH_SIZE 1000
#define WORD_SIZE 50
#define MEAN_SIZE 200
typedef struct hash_node {
char word[WORD_SIZE];
char mean[MEAN_SIZE];
struct hash_node* next;
} HashNode;
HashNode* hash_table[HASH_SIZE];
// 哈希函数
int hash(char* word) {
int val = 0;
int len = strlen(word);
for (int i = 0; i < len; i++) {
val += word[i];
}
return val % HASH_SIZE;
}
// 添加单词到哈希表中
void add_word(char* word, char* mean) {
int index = hash(word);
HashNode* node = hash_table[index];
while (node != NULL) {
if (strcmp(node->word, word) == 0) {
printf("该单词已存在于词典中\n");
return;
}
node = node->next;
}
// 创建新节点
HashNode* new_node = (HashNode*) malloc(sizeof(HashNode));
strcpy(new_node->word, word);
strcpy(new_node->mean, mean);
new_node->next = hash_table[index];
hash_table[index] = new_node;
printf("添加成功\n");
}
// 查询单词意思
void search_word(char* word) {
int index = hash(word);
HashNode* node = hash_table[index];
while (node != NULL) {
if (strcmp(node->word, word) == 0) {
printf("%s 的中文意思为 %s\n", node->word, node->mean);
return;
}
node = node->next;
}
printf("该单词不存在于词典中\n");
}
int main() {
int choice = 0;
char word[WORD_SIZE];
char mean[MEAN_SIZE];
while (1) {
printf("\n1. 添加单词\n");
printf("2. 查询单词意思\n");
printf("3. 退出程序\n");
printf("请选择: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入单词: ");
scanf("%s", word);
printf("请输入单词的中文意思: ");
getchar(); // 忽略上一个输入中的回车符
fgets(mean, MEAN_SIZE, stdin);
add_word(word, mean);
break;
case 2:
printf("请输入要查询的单词: ");
scanf("%s", word);
search_word(word);
break;
case 3:
exit(0);
default:
printf("无效的选项\n");
break;
}
}
return 0;
}
```
该程序使用哈希表来存储单词和对应的中文意思,其中哈希函数使用单词中每个字符的ASCII码之和对哈希表大小取模。程序提供了添加单词和查询单词意思的功能,通过用户选择不同的菜单选项来执行相应的操作。