Solved

Problem with strtok

Posted on 2011-03-04
7
326 Views
Last Modified: 2012-08-14
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

Open in new window

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
{
    return topOfStack == NULL;
}

// 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( );
    return topOfStack->element;
}

// 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( );
    return topItem;
}

// 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

Open in new window

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;

   cout<<"Please Enter In A Equation"<<endl;

   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;
}

Open in new window

0
Comment
Question by:brich744
7 Comments
 
LVL 32

Accepted Solution

by:
phoffric earned 500 total points
Comment Utility
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');

Open in new window

0
 
LVL 11

Expert Comment

by:DeepuAbrahamK
Comment Utility
You could try this:
cin.getline(equation,strlen(equation));
0
 
LVL 32

Expert Comment

by:phoffric
Comment Utility
>> 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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 86

Expert Comment

by:jkr
Comment Utility
>>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

by:DeepuAbrahamK
Comment Utility
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

by:DeepuAbrahamK
Comment Utility
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

by:preraksheth
Comment Utility
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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now