Reputation: 95
I am trying to write a program that will read words from a text file and insert it into a binary tree. If the word is more than 10 characters, then the word will get cut at 10 characters. I feel like I am really close to getting this but when I run the program, it crashes and I receive no errors. I tested the binary search tree with just integers and it works. I also tested reading the words from a text file without putting it in a binary tree and that also works. But when I fuse the two together.. That's where I am having issues. Also, the end of the text file is denoted by "#". Just so the break; makes sense.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Node{
string data;
Node* left;
Node* right;
};
Node* GetNewNode(string data){
Node* newNode = new Node();
newNode->data=data;
newNode->left = newNode->right = NULL;
}
Node* Insert(Node* rootPtr,string data){
if(rootPtr == NULL){
rootPtr = GetNewNode(data);
return rootPtr;
}
else if(data<= rootPtr->data){
rootPtr->left = Insert(rootPtr->left,data);
}
else {
rootPtr->right = Insert(rootPtr->right,data);
}
return rootPtr;
}
int main() {
string word;
ifstream inFile;
Node* rootPtr = NULL; // Pointer to the root node
inFile.open("example.txt");
if (!inFile) {
cout << "Unable to open text file";
}
while (inFile >> word) {
rootPtr = Insert(rootPtr,word.substr(0,10));
if (word == "#")
break;
}
inFile.close();
}
Thanks for any input!
Upvotes: 1
Views: 9375
Reputation: 8514
You need to return the newNode
from GetNewNode
.
Also, you should check for # before inserting the word, unless you want "#" in your tree.
Upvotes: 1