【发布时间】:2015-04-27 16:38:17
【问题描述】:
这是我的代码,基本上我要做的是让我的程序从我准备的文本文件中取出单词并将其传递给我的程序并计算唯一单词的数量,然后打印出来唯一的单词,旁边有计数。我已经清除了我遇到的所有错误,但现在我被卡住了,因为每次我尝试运行它时它都会崩溃。 如果有人能告诉我我在哪里做错了,我将不胜感激。
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
class BST
{
public:
BST ();
void insert (char*);
void printBST () const;
bool findNode (char*) const;
private:
struct Node;
typedef Node* NodePtr;
struct Node
{
char *word;
int count;
NodePtr left, right;
};
NodePtr root;
int compareVP (char*, char*) const;
void insert (NodePtr&, char*);
void inorderPrint (NodePtr) const;
bool findNode (NodePtr, char*) const;
};
int main ()
{
BST t;
char word[25];
ifstream readfile("infile.txt");
if(!readfile)
{
cout << "File could not be opened/found";
return 0;
}
while(readfile>> word)
{
t.insert(word);
}
if(readfile.eof())
t.printBST ();
}
BST::BST ()
{
root = NULL;
}
void BST::insert (char* word)
{
insert (root, word);
}
void BST::printBST () const
{
inorderPrint (root);
}
bool BST::findNode (char* word) const
{
return findNode (root, word);
}
int BST::compareVP (char* item1, char* item2) const
{
char* value1 = item1;
char* value2 = item2;
if (strcmp(value1,value2)==0)
return 0;
else if (strcmp(value1,value2)>0)
return 1;
else
return -1;
}
void BST::insert (NodePtr& root, char* word)
{
if (root == NULL)
{
NodePtr temp = new Node;
temp -> word = word;
temp -> left = NULL;
temp -> right = NULL;
root = temp;
}
else if (compareVP (root -> word, word) > 0)
insert (root -> left, word);
else if (compareVP (root -> word, word) < 0)
insert (root -> right, word);
else if (compareVP (root -> word, word) == 0)
root -> count++;
}
void BST::inorderPrint (NodePtr root) const
{
cout << "Word\tCount\n";
if (root != NULL)
{
inorderPrint (root -> left);
cout << root -> word << "\t";
cout << root -> count << "\n";
inorderPrint (root -> right);
}
else
cout << endl;
}
bool BST::findNode (NodePtr root, char* word) const
{
if (root == NULL)
return false;
else
{
int k = compareVP (root -> word, word);
if (k == 0)
return true;
else if (k > 0)
return findNode (root -> left, word);
else
return findNode (root -> right, word);
}
}
【问题讨论】:
-
你试过调试吗?
-
是的,我尝试过,但没有成功。事实上,这有点令人沮丧。
标签: c++ class pointers recursion binary-search-tree