这是循环击中两个输出,而不仅仅是我期望的输出

This while loop is hitting both outputs instead of just the one I expected

本文关键字:输出 不仅仅是 期望 两个 循环      更新时间:2023-10-16

因此,我已经在二进制搜索树中构建了一个字典,用户应该能够在程序中查找一个单词,该单词将从.txt文件中检索并与其显示为定义。

我正在使用关键字函数搜索每行的第一个单词,当找到正确的单词时,该函数获取整行并显示它。

这是问题,如果我在字典中搜索一个单词,那么函数就会像我期望的那样输出"找不到"。但是,每当我在文件中搜索一个单词时,我都会获得单词/def输出和"找不到的单词"消息,我只想在没有匹配时出现。

这是关键字函数的位置:

case 1:
            cout << "nEnter the word that you would like to look up:" << endl;
            cin >> word;
            wordFile.open("dictionaryWords.txt");
            B.Keyword(wordFile , word);
            wordFile.close();
            cout << endl;
            break;

,这是有关WALE循环的关键字函数。

void BSTree::Keyword(fstream & wordFile, string word) {
    string def;
    while (getline(wordFile, def)) {
        if (def.find(word) != string::npos)
        {
            cout << def << endl;
        }
    }
    cout << word << " not found" << endl;
}

您的问题是,一旦找到单词并将其打印出来,就不会'退出'循环。您应该添加休息;您的cout&lt;&lt;def&lt;&lt;端另外,您应该放一个布尔值,告诉您是否找到这样的单词:

void BSTree::Keyword(fstream & wordFile, string word) {
string def;
bool found = false;
while (getline(wordFile, def)) {
    if (def.find(word) != string::npos)
    {
        cout << def << endl;
        found = true;
        break;
    }
}
if(!found){
    cout << word << " not found" << endl;
}

对我来说似乎是无限的循环。如果找到单词,则需要在循环时添加突破。