school

thing1's amazing school repo
Log | Files | Refs | Submodules | README

rpn.c (1121B)


      1 #include <ctype.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 #include <math.h>
      6 #include "stack.h"
      7 
      8 char *readword(FILE *f) {
      9         if (getc(f) == EOF) return NULL;
     10         fseek(f, -1, SEEK_CUR);
     11 
     12 	char *word = malloc(10);
     13 	char c;
     14 	int i = 0;
     15 	while ((c = getc(f)) != ' ') {
     16         	if (c == EOF || c == '\n') break;
     17 		word[i] = c;
     18 		i++;
     19 	}
     20 	word[i] = 0;
     21 	return word;
     22 }
     23 
     24 int main() {
     25         FILE *f = fopen("test.rpn", "r");
     26         stack *s = initstack(0 ,100);
     27 
     28 	char *word;
     29 	int a, b;
     30 	while ((word = readword(f)) != NULL) {
     31         	if (!isdigit(word[0])) {
     32 			b = pop(s);
     33 			a = pop(s);
     34         		switch (word[0]) {
     35 				case '+': push(s, a+b); break;
     36 				case '-': push(s, a-b); break;
     37 				case '*': push(s, a*b); break;
     38 				case '/': push(s, a/b); break;
     39 				case '^': push(s, pow(a, b)); break;
     40 				case '~': 
     41 					push(s, a);
     42 					push(s, -b);
     43 					break;
     44 				default:
     45         				printf("unknown symbol %c\n",word[0]);
     46         				exit(1);
     47         				break;
     48         		}
     49         	}
     50         	else push(s, atoi(word));
     51         	free(word);
     52 	}
     53 	printf("%d\n", pop(s));
     54 	
     55 	deinitstack(s); 
     56 }