Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- *
- * Author: Carlos Alaniz 20244196
- * Date: 10/01/2013
- * Instructor: Zhixiang Chen;
- * Course : CMPE 3333.02
- *
- * Description: Infix to Postfix expression converter.
- **/
- #include <iostream>
- #include <string>
- #include <cstdlib>
- #include <map>
- using namespace std;
- class postfix {
- private:
- string stack;
- string post;
- string pre;
- map <char, int> ops;
- public:
- postfix(string pre) {
- post.clear();
- stack.clear();
- this->pre = pre;
- //Operator herarchy table
- ops['-'] = 1;
- ops['+'] = 1;
- ops['/'] = 2;
- ops['*'] = 2;
- ops['^'] = 4;
- ops['('] = -1;
- ops[')'] = -1;
- }
- void checksym(char sym) {
- if (stack.empty() || sym == '(') {
- stack += sym; //push into stack
- return;
- } else {
- char topOp = stack[stack.length() - 1];
- while (!stack.empty() && ops[sym] <= ops[topOp]) {
- //Pop and discard
- stack.erase(stack.end() - 1);
- if (topOp == '(' && sym == ')') {
- //stack.erase(stack.end() - 1);
- break;
- }
- post += topOp;
- if (!stack.empty()) {
- topOp = stack[stack.length() - 1];
- }
- }
- if (sym != ')')
- stack += sym;
- }
- }
- void scan() {
- for (unsigned i = 0; i < pre.length(); i++) {
- if (isdigit(pre[i])) {
- //separate numbers with a "'" ex. 380'5'85'5+++ 580.58.+5.+9.+12541.+
- while (isdigit(pre[i])) {
- post += pre[i];
- i++;
- }
- post += ',';
- i--;
- } else if (isalpha(pre[i])) {
- if (post.find(pre[i]) >= 0)
- post += pre[i];
- else
- exit(-5);
- } else if (pre[i] == ' ') {
- //ignore
- } else {
- checksym(pre[i]);
- }
- }
- for (int j = stack.length() - 1; j >= 0; j--) {
- post += stack[j]; //print the rest of the stack
- stack.erase(stack.end() - 1);
- }
- }
- string get_postfix(){
- return post;
- }
- };
- int main() {
- //string pre = "(5+8*(8056-7))*8^5-5+(9^8*8/8-5)";
- //string pre = "2*3-4/5";
- string pre = "a+b*c-d";
- postfix post(pre);
- post.scan();
- cout << post.get_postfix() << endl;
- return 0;
- }
- /**
- * Sample Output:
- *
- * input : (5+8*(8056-7))*8^5-5+(9^8*8/8-5)
- * output : 5.8.8056.7.-*+8.5.^*5.-9.8.^8.*8./5.-+
- *
- * input : 2*3-4/5
- * output : 2.3.*4.5./-
- *
- * input : a+b*c-d
- * output : abc*+d-
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement