Solved

Problem with strtok

Posted on 2011-03-04
7
329 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
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');

Open in new window

0
 
LVL 11

Expert Comment

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

Expert Comment

by:phoffric
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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 86

Expert Comment

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

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

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

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Article by: SunnyDark
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…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
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…

808 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