【发布时间】:2011-03-28 03:01:31
【问题描述】:
我正在制作一个字典程序。在将单词添加到字典之前,AddWord 函数调用 SearchForWord 函数,如果搜索函数发现传递给它的单词已经在字典中,则返回 true。
在添加函数中,我希望它移动到它实际添加单词的部分,只有当搜索函数返回 false(意味着它没有找到单词)并且我不知道如何正确表达这一点时.
编辑:我从 emacs 复制并粘贴了这一切,格式很时髦,不要讨厌。
bool Dictionary:: AddAWord(string word)
{
ofstream fout;
string fileName="#.txt";
fileName[0]=toupper(word[0]);
if(SearchForWord(word)=false){ //here i figured the SearchForWord function would be called and return either true or false
//add word
}else{
//dont add word
}
如果有帮助,这里是完整的搜索功能
bool Dictionary::SearchForWord(string word)
{
ofstream fout;
ifstream fin;
string x;
string fileName="#.txt";
fileName[0]=toupper(word[0]);
fout.open(fileName.data());
if(!fin.eof()){
while(fin>>x){
if(x=word){
cout<<"Word found during search";
return(Dictionary::success);
}
}
}else{
return(Dictionary::failure);
}
}
【问题讨论】:
-
您的字典真的那么大,必须存储在磁盘上而不是存储在内存中吗?如果没有,这里可能有一个数据结构解决方案。 SearchForWord 似乎也是错误的 - 它打开 fout 但在 fin 中搜索
-
此外,这两个函数都会对字符串进行无意义的复制,如果文件中没有单词,则不会返回任何值。不过,任何编译器都应该对此发出警告,请务必打开并查看警告。