Categories
CS

Check parentheses and change infix expression into postfix expression

//Programmer:Han
//Description:Check Parentheses and change infix expression into post expression
//Date:2012/09/14,16
//Run Environment:

#include <iostream>
#include <string>

#include <stdlib.h> //needed for atoi();

using namespace std;
int findAllParentheses(string &exp);
string infix2Postfix(string & exp);//change infix expression into postfix

int main(){
string express;
string postfixExp;
cin>>express;
cout<<express<<endl;
findAllParentheses(express);
return 0;
}
int findAllParentheses(string &exp)
{
int a[20];
int k=0;
string postfixExp;
while(exp!=“”){//Judge whether the expression is empty.
for(int i=0;i<exp.length();i++)
{
if(exp.at(i)==‘(‘)
a[k++]=i;
if(exp.at(i)==‘)’)
{

printf(“(%d,%d)n,a[k],i);

string subStrA=exp.substr(a[k]+1,i(a[k]+1));//subString without “(” and “)”
cout<<subStrA<<endl;
for (int k1=0;k1<subStrA.length();k1++)
if (!isdigit(subStrA.at(k1)))
{
string subStr1=subStrA.substr(0,k1);//the first int
string subStr2=subStrA.substr(k1+1);//the second int ; “+1″for deleting the operator
cout<<subStr1<<endl;
cout<<subStr2<<endl;
/*
int a= atoi(subStr1.c_str());
int b= atoi(subStr2.c_str());
cout<<a<<endl;
cout<<b<<endl;
cout<<a+b<<endl;*/

postfixExp.append(subStr1+‘ ‘);
postfixExp.append(subStr2+subStrA.at(k1));
cout<<postfixExp<<endl;
}
exp.erase(a[k],i(a[k])+1);
cout<<exp<<endl;
}

}
}

return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *