Postfix calculator implemented, closes NERD_tree_1

This commit is contained in:
Inex Code 2020-03-07 14:03:56 +03:00
parent 5b62521df0
commit bf45a0eec8

View file

@ -1,8 +1,9 @@
#include <errno.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int* st;
double* st;
int cnt;
int size;
} STACK;
@ -33,41 +34,102 @@ void destroy_stack(STACK* s) {
free(s);
}
void push(STACK* st, int val) {
void push(STACK* st, double val) {
if ((st -> cnt) < (st -> size)) {
st -> st[st -> cnt] = val;
(st -> cnt)++;
} else {
fprintf(stderr, "Stack is full! Stack size is %d, value to add is %d\n", st -> size, val);
fprintf(stderr, "Stack is full! Stack size is %d, value to add is %f\n", st -> size, val);
}
}
int pop(STACK* st) {
double pop(STACK* st) {
if ((st -> cnt) > 0) {
(st -> cnt)--;
return st -> st[st -> cnt];
} else {
fprintf(stderr, "Attempted to pop an empty stack\n");
return NULL;
return 0;
}
}
int main() {
printf("What's the meaning of my life?\n");
STACK* huh = init_stack(5);
push(huh, 3);
push(huh, 2);
push(huh, 4);
printf("%d", pop(huh));
printf("%d\n", pop(huh));
printf("Nice. Let's try to overflow this stack now,\n");
push(huh, 3);
push(huh, 3);
push(huh, 3);
push(huh, 3);
push(huh, 3);
printf("thx bye\n");
void add(STACK* st) {
if ((st -> cnt) > 1) {
(st -> cnt)--;
st -> st[(st -> cnt)-1] = st -> st[(st -> cnt)-1] + st -> st[st -> cnt];
}
else {
fprintf(stderr, "Not enough operands to add\n");
}
}
void substract(STACK* st) {
if ((st -> cnt) > 1) {
(st -> cnt)--;
st -> st[(st -> cnt)-1] = st -> st[(st -> cnt)-1] - st -> st[st -> cnt];
}
else {
fprintf(stderr, "Not enough operands to substract\n");
}
}
void multiply(STACK* st) {
if ((st -> cnt) > 1) {
(st -> cnt)--;
st -> st[(st -> cnt)-1] = st -> st[(st -> cnt)-1] * st -> st[st -> cnt];
}
else {
fprintf(stderr, "Not enough operands to multiply\n");
}
}
void divide(STACK* st) {
if ((st -> cnt) > 1) {
(st -> cnt)--;
st -> st[(st -> cnt)-1] = st -> st[(st -> cnt)-1] / st -> st[st -> cnt];
}
else {
fprintf(stderr, "Not enough operands to divide\n");
}
}
int parse(char *s, STACK* stack) {
double operand = 0;
char *endptr;
if (*s == '-' && *(s+1) != '\0') {
substract(stack);
return 0;
} else if (*s == '+') {
add(stack);
return 0;
} else if (*s == '/') {
divide(stack);
return 0;
} else if (*s == 'x') {
multiply(stack);
return 0;
}
errno = 0;
operand = strtod(s, &endptr);
if (errno != 0 || *endptr != '\0') return -1;
push(stack, operand);
return 0;
}
int main(int argc, char **argv) {
STACK* operands = init_stack(100);
int error;
while(*++argv) {
error = parse(*argv, operands);
if (error == -1) {
fprintf(stderr, "Error parsing operand.\n");
return(1);
}
}
int i;
for (i = (operands -> cnt); i > 0; i--) printf("%f\n", pop(operands));
return 0;
}