Solved

# applying operator to 2 numbers when operator is stored as character

Posted on 1998-10-26

The following is code for a class assignment. I get the Fully Parenthesised Expression in string FPE with no problems. The second section of assignment is to utilize the following algorithm to evaluate the expression.

1. if it is an operand, push on to the stack.

2. if it is an operator, pop two values from the stack and apply operator and push the value.

I don't see how it is possible to apply the operator which is a character, to the 2 operands that I have popped off the stack. Any feedback is greatly appreciated.

#include <iostream.h>

#include <string.h>

#include "A:\class\bstack.h"

#include <ctype.h>

typedef char string[40];

int main()

{

string expression, FPE;

unsigned i = 0, j = 0;

int x = 0, y = 0, z = 0;

char temp;

cout << "Please enter a Fully Parenthesised Expression. \n";

cout << "For example, ((2 + 4 ) * 3). \n\n";

cin.getline(expression, 39);

IntStack stk;

while (i < strlen(expression))

{

if ((expression[i] == '+' ) || (expression[i] == '-' ) || (expression[i] == '/' )||

(expression[i] == '*'))

{

stk.Push(expression[i]);

}

else if (isdigit(expression[i]) != 0 )

{

FPE[j] = expression[i];

++j;

}

else if (expression[i] == ')')

{

expression[i] = stk.Top();

FPE[j] = expression[i];

++j;

stk.Pop();

}

++i;

}

cout << " \nThe Fully Parenthisised Expression is: " << FPE << "\n\n" ;

j = 0;

while (j < strlen(FPE)) // FPE is my Fully Parenthesised Expression

{

if(isdigit(FPE[j]) != 0)

{

stk.Push(FPE[j]); // pushing the operands here

}

else

{

x = char (stk.Top());

cout << x << endl;

stk.Pop();

y = char(stk.Top());

cout << y << endl;

stk.Pop();

temp = (FPE[j]);

z = x temp y;

cout << z << '\n';

cout << temp;

stk.Push(z);

}

++j;

}

return 0;

}