#include <iostream>
#include <stack>
#include <map>
#include <string>
using namespace std;
//将中缀表达式转换为后缀表达式
string InfixToPostfix(string &str)
{
map<char, int> priority;
priority['+'] = 0;
priority['-'] = 0;
priority['*'] = 1;
priority['/'] = 1;
stack<char> mark;//处理操作符用
string nstr;
char current;
for(int i = 0; i < str.length(); ++i)
{
current = str[i];
switch(current)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
nstr.push_back(current);
break;
case '+':
case '-':
case '*':
case '/':
if(str[i-1] != ')') nstr.push_back(';');
if(mark.empty())
mark.push(current);
else
{
if(mark.top() == '(')
mark.push(current);
else if(priority[mark.top()] < priority[current])
mark.push(current);
else
{
while(!mark.empty() && priority[mark.top()] >= priority[current])
{
nstr.push_back(mark.top());
mark.pop();
}
mark.push(current);
}
}
break;
case '(':
mark.push(current);
break;
case ')':
nstr.push_back(';');
while(mark.top() != '(')
{
nstr.push_back(mark.top());
mark.pop();
if(mark.empty())
{
cerr << "Error. Unmatched '('." <<endl;
//return ;
}
}
mark.pop();
}
}
nstr.push_back(';');
while(!mark.empty())
{
nstr.push_back(mark.top());
mark.pop();
}
return nstr;
}
//处理操作符
void dealOperator(stack<char> &mark, char current, string &nstr)
{
}
//计算后缀表达式
int Calculate (string &str)
{
stack<int> integer;
char current;
string ToInt;
int a,b,sum;
for(int i = 0; i < str.length(); ++i)
{
current = str[i];
switch(current)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
ToInt.push_back(current);
break;
case ';':
integer.push(atof(ToInt.c_str()));
ToInt.clear();
break;
case '+':
b = integer.top();
integer.pop();
a = integer.top();
integer.pop();
sum = a + b;
integer.push(sum);
break;
case '-':
b = integer.top();
integer.pop();
a = integer.top();
integer.pop();
sum = a - b;
integer.push(sum);
break;
case '*':
b = integer.top();
integer.pop();
a = integer.top();
integer.pop();
sum = a * b;
integer.push(sum);
break;
case '/':
b = integer.top();
integer.pop();
a = integer.top();
integer.pop();
sum = a/b;
integer.push(sum);
break;
}
}
return integer.top();
}
int main(int argc, char *argv[])
{
string infix_exp, postfix_exp;
cout << "Enter the expression: ";
cin >> infix_exp;
postfix_exp = InfixToPostfix(infix_exp);
//cout << "The form of postfix expression: " << postfix_exp <<endl;
for(int i = 0; i != postfix_exp.size(); ++i)
{
if(postfix_exp[i] == ';')
continue;
cout << postfix_exp[i];
}
cout << endl;
int exp_sum;
exp_sum = Calculate (postfix_exp);
cout << "The sum is: "<< exp_sum <<endl;
return 0;
}