I have used a binary search tree to read in a text file, storing each word as a node, and counting how many times that word is repeated in the text file. I have been able to successfully [I]cout[/I] that information, but for some reason have been unable to read out the information to an output file.
Reading similar threads, I thought I could just put the output information into my display function, but that has not been successful. I think the problem is that my file is being opened and closed in a way that is not permitting all the information to be written to file!
Any help would be greatly appreciated!
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class node
{
public:
node(string newitem)
{
data = newitem;
counter = 1;
right = NULL;
left = NULL;
};
string data;
int counter;
node * left;
node * right;
};
class binarySearchTree
{
private:
node * root;
void insert(string x, node * & r);
void display(node * r);
public:
binarySearchTree();
//insert item into tree
void addItem(string item);
//remove given item from tree
void deleteItem(string item);
//show contents of tree
void displayItems();
};
binarySearchTree::binarySearchTree()
{
root = NULL;
}
void binarySearchTree::insert(string x, node * & r)
{
if( r == NULL )
r = new node(x);
else if(r->data == x)
{
r->counter++;
}
else
{
if( x >= r->data )
insert(x, r->right);
if( x < r->data )
insert(x, r->left);
}
}
//insert item into tree
void binarySearchTree::addItem(string item)
{
insert( item, root );
}
//remove given item from tree
void binarySearchTree::deleteItem(string item)
{
}
void binarySearchTree::display( node * r )
{
ofstream sorted;
sorted.open("storysort.txt");
if( r != NULL )
{
display(r->left);
cout << r->data << " ";
cout << r->counter << endl;
sorted << r->data << " ";
sorted << r->counter << endl;
display(r->right);
}
sorted.close();
}
//show contents of tree
void binarySearchTree::displayItems()
{
display( root );
}
int main()
{
// Open input and output files
ifstream rawdata;
rawdata.open("story.txt");
binarySearchTree ourTree;
while( ! rawdata.eof() )
{
string temp;
rawdata >> temp;
ourTree.addItem(temp);
}
ourTree.displayItems();
return 0;
}