postfix evaluation with two digits

hey guys. the code works for single digits only but not for double digits. i researched and they said i need a seperator but i think i already have that for if statement.. not sure what else is wrong. any insight is helpful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
  #include <iostream>

const int MAX = 10000;

using namespace std;
class postfix
{
private:

	int stack[MAX];
	int top, answer;;
	char *s;
public:
	postfix();
	void setexpr(char *str);
	void push(int pushitem);
	int pop();
	void calculate();
	void display();
};
postfix::postfix()
{
	top = -1;
}
void postfix::setexpr(char *str)
{
	s = str;
}
void postfix::push(int pushitem)
{
	if (top == MAX - 1)
		cout << endl << "Full";
	else
	{
		top++;
		stack[top] = pushitem;
	}
}
int postfix::pop()
{
	if (top == -1)
	{
		cout << endl << "Stack is empty";
		return NULL;
	}
	int data;
	data = stack[top];
	top--;
	return data;
}
void postfix::calculate()
{
	int exp1, exp2, exp3;
	while (*s)
	{
		if (*s == ' ' || *s == '\t')
		{
			s++;
			
		}
		if (isdigit(*s))						//if the content of s is a digit push
		{
			answer = *s - '0';
			push(answer);
		}
		else                                   //if s is not a digit pop and go thru the switch case
		{
			exp1 = pop();
			exp2 = pop();
			switch (*s)
			{
			case '+':
				exp3 = exp2 + exp1;
				break;
			case '-':
				exp3 = exp2 - exp1;
				break;
			case '/':
				exp3 = exp2 / exp1;
				break;
			case '*':
				exp3 = exp2 * exp1;
				break;
			case '%':
				exp3 = exp2 % exp1;
				break;
			default:
				cout << "invalid operator";
				
			}

			push(exp3);
		}
		s++;
	}
}
void postfix::display()			//show the result
{
	answer = pop();
	cout << "Result is: " << answer << endl;
}

int main()
{
	char s[MAX];
	postfix result;
	bool again = true;
	while (again)
	{
		cout << "\nEnter postfix expression to be evaluated : ";
		cin.getline(s, MAX); //prompt user to enter the postfix expression with a fixed size. 
		result.setexpr(s);
		result.calculate();
		result.display();
		
	}

	system("pause");
}
Last edited on
You need to change the isdigit() condition so it just add the digits to a temp string. Then when get a non-digit you can add it to your stack (and then clear the temp for reuse.)

Andy
Topic archived. No new replies allowed.