From 02653ab40d93fb7e6d07edb747fe0e07c5d60c74 Mon Sep 17 00:00:00 2001 From: thing1 Date: Thu, 30 Jan 2025 12:49:01 +0000 Subject: did many new things --- comp/work/42/rpn/rpn.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 comp/work/42/rpn/rpn.c (limited to 'comp/work/42/rpn/rpn.c') 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 +#include +#include +#include +#include +#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); +} -- cgit v1.2.3