Created
November 12, 2016 19:12
-
-
Save mostafa6765/31c21ae80d2845e864821c491ea9c409 to your computer and use it in GitHub Desktop.
Infix to Postfix c++/c plus plus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<stack>//import Stack STL | |
#include<string>//import String STL | |
#include<conio.h> | |
using namespace std; | |
string infixToPostfix(string expr); //Function declaration | |
int precendence(char arg); | |
bool isoperand(char arg); | |
bool isoperator(char arg); | |
int operatorweight(char arg); | |
bool highprecendence(char a, char b); | |
int main() | |
{ | |
string exp;//Variable to get input expression | |
cout<<"Enter the infix expression:"; | |
getline(cin,exp); | |
cout<<"Output Postfix Expression:"<<infixToPostfix(exp); | |
getch(); | |
} | |
string infixToPostfix(string expr)//Function to perform all conversion operation | |
{ | |
stack<char> stk;//Declaring a stack for conversion purpose | |
string postfix = "";//Initialize the output string as empty; | |
for(int i = 0;i < expr.length(); i++)//Scan the infix string one by one | |
if(expr[i] == '(') | |
{ | |
stk.push(expr[i]); | |
} | |
else if(expr[i] == ')') | |
{ | |
while(stk.top() != '(') | |
{ | |
postfix = postfix + stk.top(); | |
stk.pop(); | |
} | |
stk.pop(); | |
} | |
else if(isoperand(expr[i])) | |
{ | |
postfix += expr[i]; | |
} | |
else if(isoperator(expr[i])) | |
{ | |
while(!stk.empty()&& !highprecendence(expr[i],stk.top())) | |
{ | |
postfix+= stk.top(); | |
stk.pop(); | |
} | |
stk.push(expr[i]); | |
} | |
while(!stk.empty()) | |
{ | |
postfix+= stk.top(); | |
stk.pop(); | |
} | |
return postfix; | |
} | |
bool highprecendence(char a, char b)//Check for operator precendence | |
{ | |
int weighta = operatorweight(a); | |
int weightb = operatorweight(b); | |
if(weighta >= weightb) return 1; | |
return 0; | |
} | |
bool isoperator(char arg)//Check weather the character is operator | |
{ | |
if(arg == '*' || arg == '/' || arg == '+' || arg == '-') return(1); | |
else return(0); | |
} | |
bool isoperand(char arg)//Check weather the character is operand | |
{ | |
if(arg >= '0' && arg <= '9') return 1; | |
if(arg >= 'a' && arg <= 'z') return 1; | |
if(arg >= 'A' && arg <= 'Z') return 1; | |
return 0; | |
} | |
int operatorweight(char arg)//Add weight to the operator | |
{ | |
int weight = 0; | |
switch(arg) | |
{ | |
case '*': | |
case '/': | |
weight = 2; | |
break; | |
case '+': | |
case '-': | |
weight = 1; | |
break; | |
} | |
return(weight); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment