【发布时间】:2014-05-02 22:08:09
【问题描述】:
这个程序中的所有东西都可以工作,除了“搜索”函数,它根据单词是否在二叉搜索树中返回真或假。我在“main”中有一个 if 语句,它告诉用户这个词是否在树中。当我单步调试调试器时,它表示该函数在应该返回 true 时返回 true,但它直接跳到“main”中 if 语句的 else 部分。为什么是这样?它似乎工作得很好,除非它被 if 语句“查看”。例如,“test.txt”包含单词“This Program Works”,每个单词单独一行。我知道它正在将它们添加到树中,因为当我“printAll”这些词出来时......
二叉搜索树
#include "BinarySearchTree.h"
#include <iostream>
using namespace std;
bool BinarySearchTree::search(string target) {
if(target == data) {
return true;
}
else if(target < data) {
if(left == nullptr) {
return false;
}
else {
left->search(target);
}
}
else if(target > data) {
if(right == nullptr) {
return false;
}
else {
right->search(target);
}
}
}
主要
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include "BinarySearchTree.h"
using namespace std;
int main(int argc, char** argv) {
//pull in text from a .txt file, one word at a time, add each to the BinarySearchTree.
//loop and let the user enter a word, let the user know if the word was in the file or not. Have the user type 0 to quit.
cout<<"Search: ";
string target;
getline(cin,target);
while(target != "0") {
///////////////////MAIN ISSUE HERE/////////////////////////////////
if(tree.search(target) == true) {
cout<<"\""<<target<<"\""<<" found in file."<<endl;
}
else {
cout<<"\""<<target<<"\""<<" not found in file."<<endl;
}
////////////////////////////////////////////////////////////////////
cout<<"Search: ";
getline(cin,target);
}
//now that the user is content, print all words that were in the text file, in lexicographical order.
tree.printAll();
cout<<endl;
return 0;
}
事实上,我知道其他一切都很好。
【问题讨论】:
-
代码太多。请专门发布不工作的部分。
-
不是你的错误的原因,但你不需要说
==true。tree.search(target)在条件句中本身就足够了。 -
删除所有不需要的代码部分。在复制问题的同时使其尽可能小。很可能,您会在执行此操作时找出问题所在,但如果没有,我们会更轻松地为您提供帮助。
-
OT:不要使用
while (!in.eof())。 -
改用
while(getline(in,singleWord)){}
标签: c++ search boolean binary-search-tree