当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++做一个简易的英文翻译器

C++做一个简易的英文翻译器

2020年08月02日  | 移动技术网IT编程  | 我要评论

测试代码

字典.h

#ifndef 字典_H_
#define 字典_H_

#include <string>

using namespace std;
// 字典定义
typedef struct Node
{
	string cipherText;  // 密文
	string lightText; // 明文
} node;

// 字典集合
typedef struct List
{
	node item;
	List *nextItem;
} list;

class Diction
{
private:
	list * dicList; // 一本字典
	int top; // 字典长度
public:
	Diction();
	void readLine();
	void creatList();
	void showList();
	void freeList();
	void findWord(string str);
};

#endif 

字典.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
#include "字典.h"

Diction::Diction()
{
	dicList = NULL;
}

void Diction::readLine()
{
	ifstream inFile;

	inFile.open(".\\Dic.txt", ios::in);
	if (!inFile.good())
	{
		cout << "无法打开数据文件.\n";
		exit(1);
	}
	int line = 0;
	string temp;
	// 定位到流头部
	inFile.seekg(0, ios::beg);
	while (getline(inFile, temp))
	{
		++line;
	}
	// 获取列表长度
	top = line;
	inFile.close();
}

void Diction::creatList()
{
	int st;
	list * newItem, * tempItem;
	ifstream inFile;

	inFile.open(".\\Dic.txt", ios::in);
	if (!inFile.good())
	{
		cout << "无法打开数据文件.\n";
		exit(1);
	}

	// 创建一个新的节点
	newItem = new list;
	inFile >> newItem->item.cipherText >> newItem->item.lightText;
	newItem->nextItem = NULL;
	
	// dicList头指针
	// tempItem 临时尾指针
	dicList = tempItem = newItem;

	for (st = 1; st < top; st++)
	{
		newItem = new list;
		inFile >> newItem->item.cipherText >> newItem->item.lightText;
		tempItem->nextItem = newItem;
		tempItem = newItem;
	}
	tempItem->nextItem = NULL;

	inFile.close();
}

void Diction::showList()
{
	list * tempItem = dicList;

	while (tempItem != NULL)
	{
		cout << tempItem->item.cipherText << ' ' << tempItem->item.lightText << '\n';
		tempItem = tempItem->nextItem;
	}
}

void Diction::freeList()
{
	list * tempItem;

	while (dicList != NULL)
	{
		tempItem = dicList;
		dicList = tempItem->nextItem;
		free(tempItem);
	}
}

void Diction::findWord(string str)
{
	int st = 0;
	list * tempItem = dicList;
	while (tempItem != NULL)
	{
		if (tempItem->item.cipherText == str)
		{
			break;
		}
		tempItem = tempItem->nextItem;
		++st;
	}
	if (st < top)
		cout << tempItem->item.cipherText << " 译:" <<
			tempItem->item.lightText << endl;
}

测试.cpp

#include <iostream>
#include "字典.h"

int main(int argc, char *argv[])
{
	if (argc < 2)
		return 1;

	Diction diction;
	diction.readLine();
	diction.creatList();
	//diction.showList()
	
	for (int n = 1; n < argc; n++)
		diction.findWord(argv[n]);

	diction.freeList();

	return 0;
}

测试结果

完~

本文地址:https://blog.csdn.net/qq_35068659/article/details/107727847

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网