#include "lib/lib.h" #include "lib/vec.h" #include #include #include #include DECL_VEC(CharVec, char); int priority(char x) { switch (x) { case '(': return 0; break; case '+': case '-': return 1; case '*': case '/': return 2; } return 0; } CharVec readStdinToNewline() { CharVec cvec = CharVec_new(2); int ch; while (EOF != (ch = fgetc(stdin)) && ch != '\n') { CharVec_push(&cvec, ch); } return cvec; } int main() { print_header(); printf("Enter the Infix Expression:\n"); CharVec stack = CharVec_new(2); CharVec input = readStdinToNewline(); printf("The Postfix expression:\n "); while (input.elem_count != 0) { char ch = CharVec_first(&input); if (ch == ' ') { continue; } else if (isalnum(ch)) { printf("%c ", ch); } else if (ch == '(') { CharVec_push(&stack, ch); } else if (ch == ')') { char x; while ((x = CharVec_pop(&stack)) != '(') { printf("%c ", x); } } else { while (stack.elem_count != 0 && priority(*CharVec_peek(&stack)) >= priority(ch)) printf("%c ", CharVec_pop(&stack)); CharVec_push(&stack, ch); } } while (stack.elem_count != 0) { printf("%c ", CharVec_pop(&stack)); } printf("\nEnd of Program\n"); return EXIT_SUCCESS; }