Supports multi-digit postfix Evaluation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int stack[50];
int top = -1;
void push(int x) {
stack[++top] = x;
}
int pop() {
return stack[top--];
}
int main() {
char exp[200];
char *token;
int n1, n2, n3;
printf("Enter POSTFIX expression (use spaces between
numbers/operators):\n");
fgets(exp, sizeof(exp), stdin);
// remove newline
exp[strcspn(exp, "\n")] = '\0';
// split into tokens
token = strtok(exp, " ");
while (token != NULL) {
// if operator (+ - * /)
if (strlen(token) == 1 &&
(*token == '+' || *token == '-' ||
*token == '*' || *token == '/')) {
n1 = pop();
n2 = pop();
switch (*token) {
case '+': n3 = n2 + n1; break;
case '-': n3 = n2 - n1; break;
case '*': n3 = n2 * n1; break;
case '/': n3 = n2 / n1; break;
}
push(n3);
} else {
// multi-digit number
push(atoi(token));
}
token = strtok(NULL, " ");
}
printf("\nThe result = %d\n", pop());
return 0;
}