當前位置:成語大全網 - 新華字典 - 如何用C語言來制作翻譯器

如何用C語言來制作翻譯器

寫了壹個簡單的翻譯器,只提供單詞翻譯,中文到英文,英文到中文都行,妳需要首先進行字典錄入。錄入以後會自動在目錄下生成壹個dic.txt文件。

#include "stdio.h"

#include "stdlib.h"

#include "string.h"

#define FILENAME "dic.txt"

struct word //字典結構體

{

char chinese[20]; //中文

char english[20]; //英文

};

/////////////////////////////////////////////////////////////

FILE *FP; //全局文件指針

FILE * FileOpen(char FileName[]) //文件打開函數

{

FILE *fp;

if((fp=fopen(FileName,"r"))==NULL)

{

fp=fopen(FileName,"w");

cout<<"文件打開失敗重新創建記錄文件";

return fp;

}

fp=fopen(FileName,"a+");

return fp;

}

void FileClose(FILE *fp) //文件關閉函數

{

if(fclose(fp)==0)

cout<<"安全關閉"<<endl;

else

cout<<"文件關閉失敗"<<endl;

}

////////////////////////////////////////////////////////////////

void tra1() //中文翻譯成英文模塊

{

FILE *fp;

if((fp=fopen(FILENAME,"r"))==NULL)

{

printf("文件打開失敗!");

}

char tempchinese[20];

word temp;

printf("請輸入中文單詞:");

scanf("%s",tempchinese);

while(fread(&temp,sizeof(word),1,fp)==1)

{

if(strcmp(temp.chinese,tempchinese)==0)

{

printf("中文:%s 英文:%s \n",temp.chinese,temp.english);

}

}

printf("查找完畢!");

FileClose(fp);

}

//////////////////////////////////////////////

void tra2() //英文翻譯成中文模塊

{

FILE *fp;

if((fp=fopen(FILENAME,"r"))==NULL)

{

printf("文件打開失敗!");

}

char tempenglish[20];

word temp;

printf("請輸入英文單詞:");

scanf("%s",tempenglish);

while(fread(&temp,sizeof(word),1,fp)==1)

{

if(strcmp(temp.english,tempenglish)==0)

{

printf("中文:%s 英文:%s \n",temp.chinese,temp.english);

}

}

printf("查找完畢!");

FileClose(fp);

}

////////////////////////////////////////////////

void inp() //字典錄入模塊

{

FP=FileOpen(FILENAME);

word temp;

printf("請輸入英文:");

scanf("%s",temp.english);

printf("請輸入對應中文:");

scanf("%s",temp.chinese);

fwrite(&temp,sizeof(temp),1,FP);

printf("信息添加完成");

FileClose(FP);

}

////////////////////////////////////////////////

int menu() //主目錄模塊

{

int choose;

while(choose!=0)

{

printf("\n");

printf("簡易中英翻譯系統\n");

printf("1、中->英翻譯\n");

printf("2、英-中翻譯\n");

printf("3、字典錄入\n");

printf("輸入0退出系統\n");

printf("請輸入:");

scanf("%d",&choose);

switch(choose)

{

case 0:return 0;break;

case 1:tra1();break;

case 2:tra2();break;

case 3:inp();break;

}

}

}

///////////////////////////////////////////////////////

void main()

{

menu();

}