[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
Solved

# Problem with strtok

Posted on 2011-03-04
Medium Priority
336 Views
Hello Everyone,

I am writing a program that takes an equation entered by the user and converts it into a binary tree.  What I am having trouble with is when I enter an equation such as

( a + b ) * c / d

When the tokenPtr gets to the closing parenthesis it will stop reading the rest of the equation.  The code I am talking about is in Main.cpp in the while loop.

BinaryNode.cpp
``````BinaryNode.h---------------------------------------------

#ifndef BINARYNODE_H
#define BINARYNODE_H

template<class object>
class BinaryNode
{
public:
BinaryNode(object&);
void in_order(BinaryNode*);
void pre_order(BinaryNode*);
void post_order(BinaryNode*);

int size( BinaryNode * );
int height( BinaryNode * );

object *data;
BinaryNode *left;
BinaryNode *right;
};

template<class object>
BinaryNode<object>::BinaryNode(object& node)
{
data = &node;
left = NULL;
right = NULL;

}

template<class object>
void BinaryNode<object>::in_order(BinaryNode *root)
{
if(root == NULL)
return;

in_order(root->left);
cout<<root->data<<endl;
in_order(root->right);

}

template<class object>
void BinaryNode<object>::post_order(BinaryNode *root)
{
if(root == NULL)
return;

post_order(root->left);
post_order(root->right);
cout<<root->data<<endl;

}

template<class object>
void BinaryNode<object>::pre_order(BinaryNode *root)
{
if(root == NULL)
return;

cout<<root->data<<endl;
pre_order(root->left);
pre_order(root->right);

}

#endif
``````
StackLi.h

``````#ifndef STACKLI_H_
#define STACKLI_H_

#include <stdlib.h>
#include<exception>

using namespace std;

#include"BinaryNode.h"
//#include "Except.h"

// Stack class -- linked list implementation.
//
// CONSTRUCTION: with no parameters.
//
// ******************PUBLIC OPERATIONS*********************
// void push( x )        --> Insert x
// void pop( )           --> Remove most recently inserted item
// Object top( )         --> Return most recently inserted item
// Object topAndPop( )   --> Return and remove most recently inserted item
// bool isEmpty( )       --> Return true if empty; else false
// void makeEmpty( )     --> Remove all items
// ******************ERRORS********************************
// UnderflowException thrown as needed.

template <class Object>
class Stack
{
public:
Stack( );
Stack( const Stack & );
~Stack( );

bool isEmpty( ) const;
const Object & top( ) const;

void makeEmpty( );
void pop( );
void push( const Object & );
Object topAndPop( );

const Stack & operator=( const Stack & );

private:
struct ListNode
{
Object    element;
ListNode *next;

ListNode( const Object & theElement, ListNode * n = NULL )
: element( theElement ), next( n ) { }
};

ListNode *topOfStack;
};

//#include "StackLi.cpp"

// Construct the stack.
template <class Object>
Stack<Object>::Stack( )
{
topOfStack = NULL;
}

// Copy constructor.
template <class Object>
Stack<Object>::Stack( const Stack<Object> & rhs )
{
topOfStack = NULL;
*this = rhs;
}

template<>
Stack<BinaryNode<char>*>::Stack()
{
topOfStack = NULL;

}

// Destructor.
template <class Object>
Stack<Object>::~Stack( )
{
makeEmpty( );
}

// Test if the stack is logically empty.
// Return true if empty, false, otherwise.
template <class Object>
bool Stack<Object>::isEmpty( ) const
{
}

// Make the stack logically empty.
template <class Object>
void Stack<Object>::makeEmpty( )
{
while( !isEmpty( ) )
pop( );
}

// Return the most recently inserted item in the stack.
// or throw an UnderflowException if empty.
template <class Object>
const Object & Stack<Object>::top( ) const
{
//if( isEmpty( ) )
//throw UnderflowException( );
}

// Remove the most recently inserted item from the stack.
// Throw Underflow if the stack is empty.
template <class Object>
void Stack<Object>::pop( )
{
// if( isEmpty( ) )
// throw UnderflowException( );

ListNode *oldTop = topOfStack;
topOfStack = topOfStack->next;
delete oldTop;
}

// Return and remove the most recently inserted item
// from the stack.
template <class Object>
Object Stack<Object>::topAndPop( )
{
Object topItem = top( );
pop( );
}

// Insert x into the stack.
template <class Object>
void Stack<Object>::push( const Object & x )
{
topOfStack = new ListNode( x, topOfStack );
}

// Deep copy.
template <class Object>
const Stack<Object> & Stack<Object>::operator=( const Stack<Object> & rhs )
{
if( this != &rhs )
{
makeEmpty( );
if( rhs.isEmpty( ) )
return *this;

ListNode *rptr = rhs.topOfStack;
ListNode *ptr  = new ListNode( rptr->element );
topOfStack = ptr;

for( rptr = rptr->next; rptr != NULL; rptr = rptr->next )
ptr = ptr->next = new ListNode( rptr->element );
}
return *this;
}

#endif
``````
Main.cpp

``````#include<iostream>
#include<string>
#include<cstring>
#include<sstream>
#include<iterator>
#include<vector>
#include<algorithm>

using namespace std;

#include"StackLi.h"

#include"BinaryNode.h"

int main()
{
Stack<BinaryNode<char>*> ptrStack;

char equation[20];
char* tokenPtr;

cin.getline(equation, '\n');

tokenPtr = strtok(equation," ");

while( tokenPtr != NULL)
{
cout<<tokenPtr<<endl;

if(*tokenPtr == '(' || *tokenPtr == ')' || *tokenPtr == '+' || *tokenPtr=='-' || *tokenPtr == '/' || *tokenPtr == '*' || *tokenPtr == '^')
{
if(ptrStack.isEmpty())
{

BinaryNode<char> newNode(*tokenPtr);
ptrStack.push(&newNode);
}

else
{
BinaryNode<char> newNode(*tokenPtr);

newNode.right = ptrStack.topAndPop();

ptrStack.push(&newNode);

if(!ptrStack.isEmpty())
{
newNode.left = ptrStack.topAndPop();
ptrStack.push(&newNode);
}

}

}

else if(*tokenPtr == '~' || *tokenPtr == '!' || *tokenPtr == '&')
{
BinaryNode<char> newNode(*tokenPtr);

newNode.right = ptrStack.topAndPop();

ptrStack.push(&newNode);
}

else
{
BinaryNode<char> newNode(*tokenPtr);
ptrStack.push(&newNode);

}
tokenPtr = strtok(NULL, " ");

}

system("PAUSE");

return 0;
}
``````
0
Question by:brich744
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 32

Accepted Solution

phoffric earned 2000 total points
ID: 35041421
The second argument is the size.
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
http://www.cplusplus.com/reference/iostream/istream/getline/

Try this instead. Your original code was interpreting '\n' as a number which is less than the number of chars required.
``````cin.getline(equation, sizeof(equation), '\n');
``````
0

LVL 11

Expert Comment

ID: 35041576
You could try this:
cin.getline(equation,strlen(equation));
0

LVL 32

Expert Comment

ID: 35041613
>> You could try this: cin.getline(equation,strlen(equation));
1) why bother with an extra calculation by using strlen
2) what does strlen(equation) evaluate to? equation has garbage data in it, so strlen(equation) could even be 0.
0

LVL 86

Expert Comment

ID: 35041622
>>You could try this:
>>cin.getline(equation,strlen(equation));

Are you aware of how much it hurts reading that comment? Advising to use 'strlen()' to determine the size of an uninitialized character array is thoughtless at best...
0

LVL 11

Expert Comment

ID: 35041804
Oops. I am sorry. What I meant was

cin.getline(equation, sizeof(equation));

without '\n'

Will take care of these errors in the future..
0

LVL 11

Expert Comment

ID: 35041809
I haven't read the previous comments as well. I am sorry about that.My was not refreshed for a while. Will take care of these.
0

LVL 2

Expert Comment

ID: 35042997
You could use finite state model for such problem instead of an if/else based loop.
In other words, create various states for the characters in the equation, and then for each character, based on the previous state and current char, take action and define new state. That will be much clearer in terms of programming effort
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there isâ€¦
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address.Â This address might be address of another variable/address of devices/address of fuâ€¦
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor anâ€¦
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
###### Suggested Courses
Course of the Month13 days, 7 hours left to enroll