well this is my code and basically what i am trying to do is for my program to take words out of a text file that i prepared and to pass it to my program and count the amount of unique words, and to print out the unique word with the count on the side of it. i have cleared up all the errors i had but now i am stuck as it crashes every time i try to run it. i would appreciate if someone could enlighten me on where i have done wrong on.
#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;
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);
}
}
Aucun commentaire:
Enregistrer un commentaire