-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
60 lines (53 loc) · 1.8 KB
/
main.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
59
60
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#include <assert.h>
#include <math.h>
double stack[256];
unsigned char stack_index = 0;
void stack_reset() { stack_index = 0; }
unsigned char stack_size() { return stack_index; }
double stack_peek() { return stack[stack_index]; }
void stack_push(double val) {
assert(stack_index < 255);
stack[++stack_index] = val;
}
double stack_pop() {
assert(stack_index > 0);
return stack[stack_index--];
}
int main(int argc, char** argv) {
char buf[256];
regex_t regex_value, regex_operation;
regcomp(®ex_value, "[0-9]+\\.?[0-9]*", REG_EXTENDED | REG_NOSUB);
regcomp(®ex_operation, "[\\+\\-\\*\\/\\^]", REG_EXTENDED | REG_NOSUB);
while(1) {
stack_reset();
putchar('>');
fgets(buf, 256, stdin);
for(char* token = strtok(buf, " "); token != NULL; token = strtok(NULL, " ")) {
if(regexec(®ex_value, token, 0, NULL, 0) == 0) {
stack_push(strtod(token, NULL));
} else if(regexec(®ex_operation, token, 0, NULL, 0) == 0) {
double rhs = stack_pop();
double lhs = stack_pop();
switch(token[0]) {
case '+': stack_push(lhs+rhs); break;
case '-': stack_push(lhs-rhs); break;
case '*': stack_push(lhs*rhs); break;
case '/': stack_push(lhs/rhs); break;
case '^': stack_push(pow(lhs,rhs)); break;
}
} else {
printf("Giving Up: Unrecognised input: %s\n", token);
stack_reset();
break;
}
}
if(stack_size() > 0) {
printf(">> %f\n", stack_pop());
}
}
return 0;
}