电子词典C++实现

电子词典C++实现

#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class Dictorary{
public:
	Dictorary():m_head(nullptr){}
	~Dictorary(){
//		if(m_head){
        while(m_head){
			dict* temp = m_head;
			if(temp->key){delete temp->key;}
			if(temp->content){delete temp->content;}
			m_head = m_head->next;
			delete temp;
		}
	}
	/**
	* 读取字典文件的内容,构建一个链表
	* filename: 字典文件
	*/
	bool open_dict(const char* filename);
	/**
	* 读取字典文件的内容,构建一个链表
	* key: 字典key
	* content: 字典value
	*/
	bool search_word(const string& key,string& content);
private:
	typedef struct _dict{
		char * key; //字典key
		char * content; //字典value
		struct _dict* next; // next指针域
		_dict():key(nullptr),content(nullptr),next(nullptr){}
	}dict;
	dict* m_head; // 头指针
};

bool Dictorary::search_word(const string& key,string& content){
	bool ret = false;
	if(m_head == nullptr){
		cout << "cannot find word.\n";
		return false;
	}
	dict* temp = m_head;
	// 循环找
	while(temp != nullptr){
		// 这里的[1]、[6]应该是字典文件的格式。
		if(key.compare( &(temp->key[1]) ) == 0){
			content = &(temp->content[6]);
			ret = true;
			break;
		}else{
			temp = temp->next;
		}
	}
	return ret;
}

bool Dictorary::open_dict(const char* filename){
	fstream file(filename,ios_base::in );
	if(!file.is_open()){
		cout << "dict open failure.\n";
		return false;
	}else{
		cout << "dict open success.\n";
		while(!file.eof()){
			dict* temp = new dict;
			string str;
			str.clear();
			//从文件中读取一行 key
			getline(file,str);
			//copy key
			temp->key = new char[str.length()+1];
			memcpy(temp->key,str.c_str(),str.length()+1);

			str.clear();
			//从文件中读取一行 value
			getline(file,str);
			temp->content = new char[str.length()+1];
			memcpy(temp->content,str.c_str(),str.length()+1);
			//头插入
			temp->next = m_head;
			//移动头指针
			m_head = temp;
		}
		return true;
	}
}

int main(){
	//创建实例
	Dictorary dict;
	
	//open 字典文件
	if(!dict.open_dict("dict.txt")){
		getchar();
		return 0;
	}

	string str;
	string content;
	while(1){
		cout << "input your word:\n";
		getline(cin,str);
		if(str == "=exit"){
			cout << "you are exit.\n";
			break;
		}else{
			if(dict.search_word(str,content)){
				cout << content << endl;
				str.clear();
				content.clear();
			}else{
				cout << "cannot find word.\n";
			}
		}
	}
	getchar();
	return 0;
}
  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值