I have this program to read in a text file and store each word in a Binary Search Tree and keep track of the frequency of this number in the file. My outputFile should read like:
32 a
54 and
4 hello
8 will
9 would
I have the program running correctly and storing every word and frequency in a binary search tree. I have a print inorder function to print the tree in the format required... My only problem is I dont know how to write this function output to the outputFile... i know i cant call the function inside the ouputFile.is_open if, so do I have to store my results in a char * or string, any help would be appreciated?
Thanks in advance, here is my code:
class BinarySearchTree
{
private:
struct tree_node
{
tree_node* left;
tree_node* right;
string data;
int count;
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
bool isEmpty() const { return root==NULL; }
void print_inorder();
void inorder(tree_node*);
void insert(string &d);
//string results;
//string results2;
};
void BinarySearchTree::insert(string &d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
t->count = 1;
parent = NULL;
if(isEmpty()) root = t;
else
{
tree_node* curr;
curr = root;
while(curr)
{
parent = curr;
if(t->data == curr->data)
{
curr->count++;
break;
}
else if(t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if(t->data == parent->data)
{
parent = t;
}
if(t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
void BinarySearchTree::print_inorder()
{
inorder(root);
return results,results2;
}
void BinarySearchTree::inorder(tree_node* p)
{
if(p != NULL)
{
if(p->left) inorder(p->left);
cout << " " << p->count << " " << p->data << endl;
if(p->right) inorder(p->right);
}
else return;
}
int main(int argc, char *argv[])
{
BinarySearchTree b;
int ch,tmp,tmp1;
string test;
string word;
ifstream inputFile ( argv[1] );
if (inputFile.is_open())
{
while (! inputFile.eof() )
{
inputFile >> word;
b.insert(word);
}
inputFile.close();
}
else cout << "Unable to open file";
b.print_inorder();
//cout << results;
ofstream outputFile ( argv[2] );
if (outputFile.is_open())
{
//outputFile << results;
//outputFile << b.print_inorder();
outputFile.close();
}
else cout << "Unable to open file";
}