summaryrefslogtreecommitdiff
path: root/comp/work/42/rpn/rpn.c
diff options
context:
space:
mode:
authorthing1 <thing1@seacrossedlovers.xyz>2025-01-31 16:22:52 +0000
committerthing1 <thing1@seacrossedlovers.xyz>2025-01-31 16:22:52 +0000
commit45b06ac98819bfcad5f490c580d25fb0bf90c8ad (patch)
tree4f00b8a96847bccc605eea0e7154a3bd36a2fb5a /comp/work/42/rpn/rpn.c
parent00e419fa183247d6d94b7eaf274bd2ae6225c646 (diff)
parent02653ab40d93fb7e6d07edb747fe0e07c5d60c74 (diff)
performing merge
Merge branch 'master' of git://git.seacrossedlovers.xyz/school
Diffstat (limited to 'comp/work/42/rpn/rpn.c')
-rw-r--r--comp/work/42/rpn/rpn.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/comp/work/42/rpn/rpn.c b/comp/work/42/rpn/rpn.c
new file mode 100644
index 0000000..f5cd6b7
--- /dev/null
+++ b/comp/work/42/rpn/rpn.c
@@ -0,0 +1,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);
+}