您的位置:首页 > 运维架构

第十四周项目之oppo 电子词典

2015-06-06 13:47 411 查看
/*
 * Copyright (c) 2014, 烟台大学计算机学院
 * All rights reserved.
 * 文件名称:test.cpp
 * 作    者:刘佳琦
 * 完成日期:2015年 6 月 6日
 * 版 本 号:v1.0
 *
 * 问题描述:编程序,由用户输入英文词,显示词性和中文释义
 * 输入描述:查询的某个单词
 * 程序输出:查出的单词
 */
#include <fstream>
#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
string e[8000],c[8000],w[8000]; //英文和中文数组,要由文件中读入
int wordsNum=0; //词库中实际的词汇条数
int BinSeareh(int low, int high, string k);

int main( )
{
 	string key;      //查询关键词
	//将文件中的数据读入到对象数组中
	ifstream infile("dictionary.txt",ios::in);  //以输入的方式打开文件
	if(!infile)       //测试是否成功打开
	{
		cerr<<"open error!"<<endl;
		exit(1);
	}
	while (infile>>e[wordsNum]>>c[wordsNum]>>w[wordsNum])  //读取成功,则重复从文件中读
	{
		++wordsNum;
	}
	infile.close();

	//输入待查关键词并用二分查找法进行查询
	do
	{
		cout<<"请输入要查的词(0000结束):";
		cin>>key;
		if (key=="0000")
			break;
		else
		{
			int low=0,high=wordsNum-1;  //置当前查找区间上、下界的初值
			int index=BinSeareh(low, high, key);
			if (index == -1)
				cout<<"查无此词!"<<endl<<endl;
			else
				cout<<key<<"的中文意思是:"<<c[index]<<" 词性为"<<w[index]<<endl<<endl;
		}
	}
	while(1);
	cout<<"欢迎再次使用!"<<endl<<endl;
	return 0;
}
//二分查找,结果为所查词在数组中的下标
int BinSeareh(int low, int high, string k)
{
	int mid;
	while(low<=high)
	{
		mid=(low + high) / 2;
		if(e[mid]==k)
		{
			return mid; //查找成功返回
		}
		if(e[mid]>k)
			high=mid-1; //继续在e[low..mid-1]中查找
		else
			low=mid+1; //继续在e[mid+1..high]中查找
	}
	return -1; //当low>high时表示查找区间为空,查找失败
}


运行结果:



学习心得:

由于期末考在二分法上吃过亏,因此记忆比较深刻,这个项目算上这次大概是第三次了,比之前是熟练了很多。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: