summaryrefslogtreecommitdiff
path: root/comp/work/42/rpn/rpn.c
blob: f5cd6b7c86539167f3e7e698174b22435cfead8a (plain)
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
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "stack.h"

char *readword(FILE *f) {
        if (getc(f) == EOF) return NULL;
        fseek(f, -1, SEEK_CUR);

	char *word = malloc(10);
	char c;
	int i = 0;
	while ((c = getc(f)) != ' ') {
        	if (c == EOF || c == '\n') break;
		word[i] = c;
		i++;
	}
	word[i] = 0;
	return word;
}

int main() {
        FILE *f = fopen("test.rpn", "r");
        stack *s = initstack(0 ,100);

	char *word;
	int a, b;
	while ((word = readword(f)) != NULL) {
        	if (!isdigit(word[0])) {
			b = pop(s);
			a = pop(s);
        		switch (word[0]) {
				case '+': push(s, a+b); break;
				case '-': push(s, a-b); break;
				case '*': push(s, a*b); break;
				case '/': push(s, a/b); break;
				case '^': push(s, pow(a, b)); break;
				case '~': 
					push(s, a);
					push(s, -b);
					break;
				default:
        				printf("unknown symbol %c\n",word[0]);
        				exit(1);
        				break;
        		}
        	}
        	else push(s, atoi(word));
        	free(word);
	}
	printf("%d\n", pop(s));
	
	deinitstack(s); 
}