【C语言】《词典翻译》小程序

【C语言】《词典翻译》小程序

这是一款简单的“词典翻译”小程序,根据本地词库,简单实现,没有套壳,对于文件读写操作以及指针的精确掌握有着一定的帮助,希望读者能有所收获!其余我就不说太多了,代码有注释,词库文件在附件中,由于做测试使用,未添加太多词库,有时间爬一份完整的词库并将程序做成图形界面再发布。

使用方法

在其命令界面,根据提示输入单词(词库已录入),回车进行查找,其余均有提示,不再赘述。

/********************************************
 * 1.创建结构体存储单词和翻译
 * 2.读取单词,格式化存储对应的对空间中
 * 3.单词查找
 * 4.销毁堆空间
 *******************************************/
//#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ONEK 1024

typedef struct dict
{
	char *Word;
	char *Trans;
}DICT;

DICT* list = NULL;

int GetWord()
{
	//文件指针
	FILE* fp = fopen("./dict.txt", "r");

	if (!fp)
	{
		printf("词库加载失败\n");
		return -1;
	}

	//开辟对应堆空间读取词库
	list = (DICT*)malloc(sizeof(DICT) * 50);

	//开辟临时空间存储读取词库内容
	char* temp = (char*)malloc(sizeof(char) * ONEK);

	int i = 0;

	//读取词库文本加载到内存当中
	while (!feof(fp))
	{
		memset(temp, 0, ONEK);
		fgets(temp, ONEK, fp);
		temp[strlen(temp) - 1] = 0;		//temp末尾\n置为0
		list[i].Word = malloc(sizeof(char) * strlen(temp) + 1);
		if (!list[i].Word)	return -2;
		strcpy(list[i].Word, temp);

		memset(temp, 0, ONEK);
		fgets(temp, ONEK, fp);
		temp[strlen(temp) - 1] = 0;
		list[i].Trans = malloc(sizeof(char) * strlen(temp) + 1);
		if (!list[i].Trans)	return -2;
		strcpy(list[i].Trans, &temp[6]);	//去掉字符串开始Trans:(格式化字符串)

		i++;
	}
	
	fclose(fp);
	free(temp);
	return i;
}


int SearchWord(int size)
{
	char* word = (char*)malloc(sizeof(char) * 30);
	char* trans = (char*)malloc(sizeof(char) * ONEK);
	if (!word || !trans)
		return -1;

	while (1)
	{
		memset(word, 0, 30);
		memset(trans, 0, ONEK);
		printf("输入单词:[输入\":exit\"退出]\n");
		//gets(word);
		scanf("%s",word);

		if (!strcmp(word, ":exit"))
		{
			printf("已退出查找\n");
			break;
		}

		for (int i = 0; i < size; i++)
		{
			if (!strcmp(word, list[i].Word))
			{
				strcpy(trans, list[i].Trans);
				break;
			}
		}

		if (!strlen(trans))
			printf("词库未录入\n");
		
		else
			printf("%s\n", trans);
	}

	free(word);
	free(trans);
	return 0;
}

int DestroySpace(int size)
{
	if (!list)
		return 0;
	for (size_t i = 0; i < size; i++)
	{
		free(list[i].Word);
		free(list[i].Trans);
	}

	free(list);
	list = NULL;
	return 0;
}



int main()
{
	int size = GetWord();

	if (!size)
		printf("词库加载失败!\n");

	SearchWord(size);

	DestroySpace(size);


	return 0;
}

运行界面部分词库

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我姥爷是校长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值