项目实践---字典

来源:互联网 发布:淘宝店图片轮播素材 编辑:程序博客网 时间:2024/06/07 17:30

//首先在C盘建个文件:

‍love    爱
I       我
choice 选择

//创建zidian.cpp

#include<iostream>
#include"dic.h"
using namespace std;
int main()
{
   cout<<"--欢迎使用四六级字典--"<<endl;
cout<<"\t1:翻译单词"<<endl
   <<"\t2:添加单词"<<endl
   <<"\t3:每天一记"<<endl
   <<"\t4:退出"<<endl;
cout<<"************************"<<endl;
dic zidian;
string word;

int choice;
do
{
   cout<<"请选择你的操作:"<<endl;
   cin>>choice;
   switch(choice)
   {
   case 1:cout<<"输入你要翻译的单词:"<<endl;
    cin>>word;
    cout<<word<<": "<<zidian.EnglisttoChinese(word)<<endl;
    break;
   case 2:cout<<"输入你要添加的单词:"<<endl;
    cin>>word;
    cout<<word<<": "<<zidian.EnglisttoChinese(word)<<endl;
    break;
  
   case 4:cout<<"退出系统"<<endl;
    exit(1);
    break;
   default:cout<<"输入错误!"<<endl;
    exit(1);
    break;
   }
}while(choice==1 || choice==2 || choice==3 );


return 0;
}

//创建dic.h

#include<string>
#include<iostream>
#include<fstream>
#include<map>
using namespace std;// 这个不加就会出错
class dic
{
public:
dic();


string EnglisttoChinese(string str);
private:
map<string,string> EtoC;
};

dic::dic()
{

    string Englishword;
string Chineseword;
ifstream ifile;
ifile.open("c:\\英汉对照.txt"); 
if(!ifile)
{
   cout<<"ERROR!"<<endl;
   exit(1);
}
while(ifile>>Englishword>>Chineseword)
{
   EtoC.insert(map<string,string>::value_type(Englishword,Chineseword));


ifile.close();

}


string dic::EnglisttoChinese(string str)
{
   map<string,string>::const_iterator          //在字典里查找你要查的英文单词
   iter=EtoC.find(str);
if(iter==EtoC.end())
   return "没有这个单词";
else
   return iter->second;                  //返回单词的翻译
}

0 0