Originally Posted by
AndrewHunter
I read up on it before the project, and I incorporated it into my program.
Originally Posted by
AndrewHunter
This was my first thought. I turned to c strings as a suggestion from the professor, though.
Originally Posted by
AndrewHunter
Unless you are required to create your own stack class, use std::stack.
I was.
Here is my infix->postfix function
Code:
template <typename E>
Stack<E> Stack<E>::infix2Post() throw(MismatchedParen)
{
Stack<char> opStk(50);
Stack<char> outStk(50);
int i=0;
while(isOperator(S[i])||isOperand(S[i])||S[i]=='('||S[i]==')')
{
if(isOperand(S[i]))
{
outStk.push(S[i]);
i++;
}
if(isOperator(S[i]))
{
while((!opStk.empty())&&((S[1]!='^'&& precedence(S[i])<=precedence(opStk.top()))||
(S[1]=='^'&&precedence(S[i])<precedence(opStk.top()))))
{
outStk.push(opStk.top());
opStk.pop();
}
opStk.push(S[i]);
i++;
}
if(S[i]=='(')
{
opStk.push('(');
i++;
}
if(S[i]==')')
{
while(opStk.top()!='(')
{
outStk.push(opStk.top());
opStk.pop();
}
if(opStk.top()=='(')
{
opStk.pop();
i++;
}
if(opStk.empty())
throw MismatchedParen("No closing parenthesis");
}
}
while(!(opStk.empty()))
{
if(opStk.top()=='(' || opStk.top()==')')
throw MismatchedParen("No closing parenthesis");
outStk.push(opStk.top());
opStk.pop();
}
return outStk;
}
And my driver:
Code:
#include <iostream>
#include"Stack.h"
#include"Stack.cpp"
#include"Exception.h"
#include<string>
#include<cstring>
#include<cstdlib>
using namespace std;
#pragma warning( disable : 4290 )
int main()
{
char infix[50];
char temp[50];
Stack<char> inStk(50);
cout<<"Enter an expression: ";
cin.getline (infix, 50, '\n' );
strcpy(temp, infix);
cout<<infix<<endl;
cout<<"NOW PRINTING LOCAL INFIX CHAR ARRAY"<<endl;
char* token=NULL;
token = strtok(temp, " \n");
while (token != NULL)
{
cout<<token<<endl;
token = strtok(NULL, " \n");
}
strcpy(temp, infix);
cout<<"\nNOW PUSHING INFIX CHAR ARRAY TO INFIXSTACK CLASS ARRAY"<<endl;
inStk.str2Stack(temp);
cout<<"\n\nNOW PRINTING INFIXSTACK CLASS ARRAY"<<endl;
inStk.printStack();
strcpy(temp, infix);
cout<<"\n\nNOW COPYING INFIXSTACK CLASS ARRAY TO POSTFIXSTACK CLASS ARRAY"<<endl;
Stack<char> postStk(50);
postStk=inStk;
postStk.printStack();
cout<<"\n\nNOW CONVERTING INFIXSTACK CLASS ARRAY TO POSTFIXSTACK CLASS ARRAY"<<endl;
postStk=inStk.infix2Post();
cout<<"\n\nNOW PRINTING POSTFIXSTACK CLASS ARRAY"<<endl;
postStk.printStack();
cout<<"\n\nNOW PRINTING EVALUATING POSTFIXSTACK CLASS ARRAY"<<endl;
cout<<postStk.evalPost()<<endl;
return 0;
}