电子词典C++实现
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
class Dictorary{
public:
Dictorary():m_head(nullptr){}
~Dictorary(){
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;
}
}
bool open_dict(const char* filename);
bool search_word(const string& key,string& content);
private:
typedef struct _dict{
char * key;
char * content;
struct _dict* 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){
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();
getline(file,str);
temp->key = new char[str.length()+1];
memcpy(temp->key,str.c_str(),str.length()+1);
str.clear();
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;
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;
}