Hey everyone, I am converting a string to an Expression tree. I made a build function and it seems to work fine, but I get a seg fault for some reason. After each token from the input string I put some output statements to see if they work and they all seem to. I call this function in the constructor and after it has ended, everything is fine so I'm not even sure if there is an error in my logic. Can you check it out? Thanks everyone.
void ExprTree::build(const string& str)
{
//create an input string stream
istringstream ist(str);
string toke;
stack<TNode*> stack;
TNode* TNptr;
while(ist >> toke)
{
//check to see if the token is an operator, variable, or number
if((toke == "/") || (toke == "+") || (toke == "-") ||
(toke == "*"))
{
//if token is an operator, create a new node with the token being the
//operand. Set the right pointer to the top value in the stack, pop
//the stack, set the new top value in the right link of the new node,
//pop the stack again
TNptr = new TNode(toke[0], 0.0);
TNptr->right = stack.top();
stack.pop();
TNptr->left = stack.top();
stack.pop();
stack.push(TNptr);
}
elseif(toke.size() == 1 && isalpha(toke[0]))
{
// if the token is a letter, create a new node and push it on the
//stack
TNptr = new TNode(toke[0], 0.0);
stack.push(TNptr);
}
else
{
//if the token is a digit, create a new node, convert the string to a
//double and use it a parameter for the new node. Then push it onto the
//stack
TNptr = new TNode('#', atof(toke.c_str()));
stack.push(TNptr);
}
}
//make the root the last element of the stack then pop it.
root = stack.top();
stack.pop();
return;
}
Here is the constructor:
1 2 3 4 5 6
ExprTree::ExprTree(const string& expr)
{
//call build to build the tree
build(expr);
}