设有一个已经排序的英文词典文档,每个词条的格式为: 词条/词性/例句
例如: book/n./This is a book.
Student/n./I am a student.
Teacher/n./I am a teacher.
试编写一个程序,根据二凡查找的原理,在文件中查找指定单词的词条,并输出词条信息.
#include<iostream>
#include<cstring>
using namespace std;
const int N = 100;
typedef struct word{//词典结构体
char Entry[N];//词条
char nature[N];//词性
char example[N];//例句
};
void findWord(word w[], char s[], int start, int end){
int low = start, high = end;
while (low < high){
int mid = (low + high) / 2;
if (!strcmp(w[mid].Entry, s)){
cout << w[mid].Entry << " " << w[mid].nature << " " << w[mid].example;
return;
}
else if (strcmp(w[mid].Entry, s) > 0){
high = mid - 1;
}
else{
low = mid + 1;
}
}
}
int init(word w[], FILE *fp){//从文件中读入资源到词典,返回值为词典长度
char ch = fgetc(fp);
int lengthW = 0;//词典长度
int j = 0;
while (ch != EOF){
while(ch!='/'&&ch!=EOF){
w[lengthW].Entry[j++] = ch;
ch = fgetc(fp);
}
ch = fgetc(fp);
w[lengthW].Entry[j] = '\0';
j = 0;
while (ch != '/'&&ch != EOF){
w[lengthW].nature[j++] = ch;
ch = fgetc(fp);
}
ch = fgetc(fp);
w[lengthW].nature[j++] = '\0';
j = 0;
while (ch != '\n'&&ch != EOF){
w[lengthW].example[j++] = ch;
ch = fgetc(fp);
}
ch = fgetc(fp);
w[lengthW].example[j] = '\0';
j = 0;
lengthW++;
}
return lengthW;
}
void print(word w[], int n){//输出测试函数
for (int i = 0; i < n; i++){
cout << w[i].Entry <<" "<< w[i].nature <<" "<< w[i].example<<endl;
}
}
int main(){
FILE *fp;
if ((fp = fopen("F:\\Text.txt", "r")) == NULL){
printf("cannot open this file\n");
exit(0);
}
else{
cout << "succ"<<endl;
}
word w[N];//创建一个词典
int n = init(w, fp);//初始化词典
print(w, n);
cout << "find result : ";
findWord(w, "Student",0,n - 1);//寻找学生.
fclose(fp);//关闭文件
system("pause");
return 0;
}