Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include <ctype.h>
- typedef double number_t;
- typedef char op_t;
- void push (number_t);
- number_t pop ();
- bool empty ();
- bool is_operator (char);
- bool is_number (char);
- number_t apply_operator (op_t, number_t, number_t);
- number_t parse_number ();
- void trim_left ();
- void read_buffer ();
- void evaluate_buffer ();
- // --
- #define STACK_SIZE 256
- #define BUFFER_SIZE 512
- char buffer[BUFFER_SIZE + 1];
- number_t stack[STACK_SIZE];
- int sp = 0, bp = 0;
- void push (number_t num)
- {
- if (sp >= STACK_SIZE)
- {
- // stack overflow!!!
- return;
- }
- stack[sp++] = num;
- }
- number_t pop ()
- {
- if (empty())
- {
- // stack underflow!!
- return 0;
- }
- return stack[--sp];
- }
- bool empty ()
- {
- return sp == 0;
- }
- bool is_operator (char c)
- {
- return c == '+' ||
- c == '-' ||
- c == '*' ||
- c == '/';
- }
- bool is_number (char c)
- {
- return c == '.' || isdigit(c);
- }
- number_t apply_operator (op_t op, number_t a, number_t b)
- {
- switch (op)
- {
- case '+': return a + b;
- case '-': return a - b;
- case '*': return a * b;
- case '/': return a / b;
- default:
- return 0; // this case likely won't be reached
- }
- }
- number_t parse_number ()
- {
- number_t num = 0,
- mag = .1;
- for (; isdigit(buffer[bp]); bp++)
- num = (num * 10) + (buffer[bp] - '0');
- if (buffer[bp] == '.')
- for (bp++; isdigit(buffer[bp]); bp++)
- {
- num += (buffer[bp] - '0') * mag;
- mag *= .1; // this is probably inefficient :|
- }
- return num;
- }
- void trim_left ()
- {
- while (isspace(buffer[bp]))
- bp++;
- }
- void read_buffer ()
- {
- int c, i;
- for (i = 0; i < BUFFER_SIZE; i++)
- if ((c = getchar()) == '\n')
- break;
- else
- buffer[i] = c;
- buffer[i] = '\0';
- bp = 0;
- }
- void evaluate_buffer ()
- {
- sp = 0;
- for (trim_left(); buffer[bp]; trim_left())
- {
- if (is_operator(buffer[bp]))
- {
- op_t op = buffer[bp++];
- number_t b = pop();
- number_t a = pop();
- push(apply_operator(op, a, b));
- }
- else if (is_number(buffer[bp]))
- push(parse_number());
- else
- {
- // syntax error!
- break;
- }
- }
- }
- int main ()
- {
- for (;;)
- {
- printf("> ");
- read_buffer();
- evaluate_buffer();
- while (!empty())
- printf("%.3f ", pop());
- printf("\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement