问题及代码:
运行结果:
知识点总结:
电子词典结构体版。
/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:words.cpp
*作 者:单昕昕
*完成日期:2014年12月21日
*版 本 号:v1.0
*
*问题描述:电子词典结构体版。
*程序输入:英文单词。
*程序输出:词性和中文释义。
*/
#include <fstream> //操作文件必写
#include<iostream>
#include<cstdlib>
using namespace std;
struct Word
{
string english;
string chinese;
string word_class;
};
int main( )
{
Word words[8000];
int wordsNum=0;
string key;
//以输入的方式(ios::in)打开文件
ifstream infile("dictionary.txt",ios::in); //测试是否成功打开,打开失败时(如要读的数据文件不存在)退出
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
while (!infile.eof())
{
infile>>words[wordsNum].english;
infile>>words[wordsNum].chinese;
infile>>words[wordsNum].word_class;
++wordsNum;
}
infile.close(); <span style="white-space:pre"> </span> //读入完毕一定要关闭文件
cout<<"请输入您想要查找的单词(输入0000时退出程序):"<<endl;
while (cin>>key&&key!="0000") //一直输入,直到输入0000
{
int low=0,high=wordsNum-1,mid,flag1,flag2;
while(low<=high)
{
mid=(low+high)/2;
if(words[mid].english==key)
{
flag1=1;
flag2=mid;
break;
}
else if(words[mid].english>key)
high=mid-1;
else
low=mid+1;
}
if(flag1==0)
{
cout<<"对不起,查无此词。"<<endl;
}
if(flag1==1)
{
cout<<key<<"-->"<<words[flag2].word_class<<"-->"<<words[flag2].chinese<<endl;
flag1--;
}
}
return 0;
}
运行结果:
知识点总结:
电子词典结构体版。
学习心得:
主要是如果查无此词要怎么办,我改了好多次才解决好。