Our task is to write a Binary Search Tree and the data has to be input from a .txt file where in the data is held as such
12345678
Each digit is a new node in the tree to be inserted. My Binary Tree is working because I can just enter raw numbers into the insert functions and it works and prints properly but when I try and draw the data in from the txt file i comes up with random numbers. The following example is a run where the file contained the digits
123
Example:
Please enter a file name: 2l.txt
You entered file name: 2l.txt
File was successfully opened
element = 1
Key: 49 SearchCost = 1
element =
Key: 49 SearchCost = 1
Key: 10 SearchCost = 2
element = 2
Key: 49 SearchCost = 1
Key: 10 SearchCost = 2
Key: 50 SearchCost = 2
element =
Abort (core dumped)
Below I have posted the code for my main.
#include "BinarySearchTree.h"
#include <fstream>
#include <string>
using namespace std;
int main() {
BinarySearchTree* tree = new BinarySearchTree();
ifstream istream;
string fileName;
cout << "Please enter a file name: ";
cin >> fileName;
cout << "You entered file name: " << fileName << endl;
//Test whether file is opened
istream.open(fileName.c_str());
if (istream.is_open())
{
cout << "File was successfully opened" << endl;
}
else
{
cout << "Error opening file" << endl;
}
char element;
while(!istream.eof()) {
element = istream.get();
cout << "element = " << element << endl;
tree->insert(element);
BinaryNode::PrintTreeNode pt;
tree->getRoot()->preOrderTraversal(pt);
}
BinaryNode::PrintTreeNode pt;
tree->getRoot()->preOrderTraversal(pt);
return 0;
}
I have also zipped the input file and the 4 code files in case anyone is interested.
Thanks in advance