Dictionary.h
#ifndef H_DICTIONARY
#define H_DICTIONARY
#include <string>
#include <set>
#include <fstream>
#include <algorithm>
#define FILTER ";"//用于分隔单词的字符,可以更改,比如添加空格"; "
class Dictionary
{
public:
Dictionary(){};
//直接从词典文件构造
explicit Dictionary(const std::string& filename,const std::string& filter=FILTER)
{
readfile(filename,filter);
}
//读取词典文件
void read(const std::string& filename,const std::string& filter=FILTER)
{
dict.empty();
readfile(filename,filter);
}
bool search(const std::string& word);
private:
void readfile(const std::string& filename,const std::string& filter);//由于read和构造函数内容相近,提取出来作为一个单独的函数供其调用
private:
std::set<std::string> dict;//使用set确保没有重复的单词
};
bool Dictionary::search(const std::string& word)//使用标准库find算法查找
{
return (std::find(dict.begin(),dict.end(),word)!=dict.end());
}
void Dictionary::readfile(const std::string& filename,const std::string& filter)
{
std::ifstream file(filename.c_str(),std::ios::out);
//打开文件失败,退出
if(!file)
{
std::cerr<<"Can't read dictionary from "<<filename<<std::endl;
exit(-1);
}
std::string line;
while(std::getline(file,line))//读取一行
{
std::string::size_type pos=0;
std::string::size_type pre_pos=pos;
std::string word;
//查找分隔符,以界定单词
while((pos=line.find_first_of(filter,pos))!=std::string::npos)
{
word=line.substr(pre_pos,pos-pre_pos);
if(word.size())
dict.insert(word);
pre_pos=++pos;
}
//处理行末单词之后没有分隔符的情况
word=line.substr(pre_pos,std::string::npos);
if(word.size())
dict.insert(word);
}
}
#endif
main.cpp
#include <iostream>
#include "dictionary.h"
int main(int argc, char* argv[])
{
std::string filename;
std::cout<<"Please input the dictionary file name:";
std::cin>>filename;
//直接从文件生成词典
Dictionary dic(filename);
std::string word;
std::cout<<"Please input the word to be searched:";
std::cin>>word;
if(dic.search(word))
{
std::cout<<'\"'<<word<<"\" have been found in the dictionary.\n";
}
else
{
std::cout<<"Can't find the word in the dictionary.\n";
}
return 0;
}
[此贴子已经被作者于2006-10-30 17:41:51编辑过]