这是循环击中两个输出,而不仅仅是我期望的输出
This while loop is hitting both outputs instead of just the one I expected
因此,我已经在二进制搜索树中构建了一个字典,用户应该能够在程序中查找一个单词,该单词将从.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;
}
对我来说似乎是无限的循环。如果找到单词,则需要在循环时添加突破。
相关文章:
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- COUT 无法提供输出可能是由于内联组装
- 为什么我们要做"INT_MAX/10"而不仅仅是INT_MAX?
- 为对象分配整数.输出将是什么?
- 为什么 std::vector 需要 is_trivial 才能按位移动,而不仅仅是is_trivially_copya
- 为什么在这个C++问题中使用const_iterator而不仅仅是迭代器?
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 如果要求比较器是严格的总排序,而不仅仅是严格的弱排序,C++标准算法会更快吗?
- 程序的输出不是来的,它是一个链表程序
- 我的输出结果是 0 英寸C++.可能是什么问题
- 为什么我们必须在 C++ 中释放数组数组,而不仅仅是整个"matrix"
- 存储和打印字符,但输出不是预期的
- 输出不是我想要C++的
- 十进制文字不仅仅是LONG_LONG_MAX
- 为什么非放置"新建"和"删除"内置于语言中,而不仅仅是常规函数?
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- C++:为什么最后一个输出不是地址以及如何获取值 9
- 这是循环击中两个输出,而不仅仅是我期望的输出