rpn.c (1165B)
1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <string.h> 4 5 #include <math.h> 6 7 #include "stack.h" 8 9 int main(int argc, char **argv){ 10 stack *s = initstack(0, 64); 11 char in[128] = {0}; 12 13 if (argc > 1){ 14 for (int i = 1; i < argc; i++){ 15 strcat(in, argv[i]); 16 strcat(in, " "); 17 } 18 } else fgets(in, 128, stdin); 19 20 for (int i = 0; i < 128; i++) if (in[i] == '\n') in[i] = '\0'; 21 fflush(stdin); 22 23 int r; 24 25 int a; 26 int b; 27 28 char *tok = strtok(in, " "); 29 while (tok != NULL){ 30 switch (tok[0]) { 31 case '+': 32 a = s->pop(s); 33 b = s->pop(s); 34 s->push(s, b+a); 35 break; 36 case '-': 37 a = s->pop(s); 38 b = s->pop(s); 39 s->push(s, b-a); 40 break; 41 case '*': 42 a = s->pop(s); 43 b = s->pop(s); 44 s->push(s, b*a); 45 break; 46 case '/': 47 a = s->pop(s); 48 b = s->pop(s); 49 s->push(s, b/a); 50 break; 51 case '^': 52 a = s->pop(s); 53 b = s->pop(s); 54 s->push(s, pow(b, a)); 55 break; 56 case '.': 57 r = s->pop(s); 58 printf("%d\n", r); 59 break; 60 default: 61 s->push(s, atoi(tok)); 62 break; 63 } 64 tok = strtok(NULL, " "); 65 if (tok == NULL){ 66 r = s->pop(s); 67 printf("%d\n", r); 68 break; 69 } 70 } 71 s->free(s); 72 return 0; 73 }