Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 这个while循环同时命中两个输出,而不仅仅是我所期望的输出_C++ - Fatal编程技术网

C++ 这个while循环同时命中两个输出,而不仅仅是我所期望的输出

C++ 这个while循环同时命中两个输出,而不仅仅是我所期望的输出,c++,C++,因此,我在二元搜索树中构建了一个字典,用户应该能够在程序中查找一个单词,该单词将从.txt文件中检索并显示其定义 我使用一个关键字函数来搜索每行的第一个单词,当找到正确的单词时,该函数将获得整行并显示它 问题是,如果我搜索字典中没有的单词,函数会像我预期的那样输出“word not found”。但是,每当我搜索文件中的单词时,我都会得到单词/def输出和“word not found”(未找到单词)消息,我只想在没有匹配项时显示这些消息 这里是调用关键字函数的地方: case 1:

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

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

问题是,如果我搜索字典中没有的单词,函数会像我预期的那样输出“word not found”。但是,每当我搜索文件中的单词时,我都会得到单词/def输出和“word not found”(未找到单词)消息,我只想在没有匹配项时显示这些消息

这里是调用关键字函数的地方:

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;
案例1:
单词;
打开(“dictionaryWords.txt”);
关键词(wordFile,word);
close();

cout您的问题是,一旦找到单词并打印出来,就不会“退出”循环。你应该加上休息;对我来说,你的cout似乎是一个无限循环。如果找到单词,则需要添加中断while循环。

听起来像是要中断while循环。更像是在if中的
return
,在
cout
之后。投票以键入方式结束<谢谢大家!我把它改为bool而不是void,并在找到时在“if”语句中添加了“return”,从而解决了问题。
break
不会停止打印
not found
。您可以通过将
break
替换为
return
,来保存所有的工作。是的,我想这是一种更简单的方法,我将整个函数改为a
bool
然后使用
return
在找到时退出循环,谢谢你们的帮助。没问题!很高兴我能帮忙
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;
}
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;
}