-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpostfix-calc.c
58 lines (54 loc) · 1.15 KB
/
postfix-calc.c
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
#include <stdio.h> //printf()
#include <stdlib.h> //malloc(), free(), exit(), EXIT_FAILURE, atoi()
#include <ctype.h> //isdigit()
#include <string.h> //(obsolete)?
#include <assert.h> //assert()
#include "stack.h" //custom "class" stack
// helper-function
int isnum(char *a) {
if(*a == '\0') {
return 1;
} else {
return isdigit(*a) && isnum(a+1);
}
}
// Postfix-Rechner
int calc(char *expr[], int expr_length) {
int k, n1, n2;
stack *s = NULL;
for(k = 0; k < expr_length; k++) {
if(isnum(expr[k])) {
stack_push(&s, atoi(expr[k]));
} else { // Operator erwartet
n2 = stack_pop(&s);
n1 = stack_pop(&s);
switch(expr[k][0]) {
case '+':
stack_push(&s, n1+n2);
break;
case '-':
stack_push(&s, n1-n2);
break;
case '*':
stack_push(&s, n1*n2);
break;
case '/':
stack_push(&s, n1/n2);
break;
default:
printf("Syntax error: %s unexpected\n", expr[k]);
exit(EXIT_FAILURE);
}
}
}
n1 = stack_pop(&s);
if(stack_isempty(&s)) return n1;
else {
printf("Missing operand\n");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[]) {
printf("%d\n", calc(argv+1, argc-1));
return 0;
}