Infix evaluation (中序的四则预算)

I have not figured out the parentheses and points yet.

int infix(string exp)
{
	stack<int> numStack;  //for parsing the operand
	stack<int> operandStack;  //for store the operands
	stack<char> operatorStack; // operators

	for(int i=0; i<exp.size(); i++)
	{
		if(exp[i] == ' ')
		{
			break;
		}
		else if(exp[i]<='9' && exp[i]>='0')
		{
			numStack.push(exp[i]-'0');
		}
		else if(exp[i]=='*' || exp[i]=='/' )
		{
			int op = 0;
			int n = 0;

			while(!numStack.empty())
			{
				op += numStack.top()*pow(10.0,n);
				numStack.pop();
				n++;
			}
			operandStack.push(op);
			operatorStack.push(exp[i]);
		}
		else if(exp[i]=='+' || exp[i]=='-')
		{
			int op = 0;
			int n = 0;

			while(!numStack.empty())
			{
				op += numStack.top()*pow(10.0,n);
				numStack.pop();
				n++;
			}
			if(operatorStack.empty())
			{
					operandStack.push(op);
					operatorStack.push(exp[i]);
			}
			else
			{
				if(operatorStack.top() == '*')
				{
					op *= operandStack.top ();
					operandStack.pop();
					operandStack.push(op);
					operatorStack.pop();
					operatorStack.push(exp[i]);
				}
				else if(operatorStack.top() == '/')
				{
					op = operandStack.top ()/op;
					operandStack.pop();
					operandStack.push(op);
					operatorStack.pop();
					operatorStack.push(exp[i]);
				}
				else
				{
					operandStack.push(op);
					operatorStack.push(exp[i]);
				}
			}
		}
		else if(exp[i] == '=')
		{
			int op = 0;
			int n = 0;
			while(!numStack.empty())
			{
				op += numStack.top()*pow(10.0,n);
				numStack.pop();
				n++;
			}
			if(operatorStack.top() == '*')
			{
				op *= operandStack.top();
				operandStack.pop();
				operandStack.push(op);
				operatorStack.pop();
			}
			else if(operatorStack.top() == '/')
			{
				op = operandStack.top()/op;
				operandStack.pop();
				operandStack.push(op);
				operatorStack.pop();
			}
			else
			{
				operandStack.push(op);
			}
			while(!operatorStack.empty())
			{
				if(operatorStack.top() == '+')
				{
					int o1 = operandStack.top();
					operandStack.pop();
					int o2 = operandStack.top();
					operandStack.pop();
					operandStack.push(o1+o2);
					operatorStack.pop();
					cout<<o1<<"+"<<o2<<endl;
				}
				else if(operatorStack.top() == '-')
				{
					int o1 = operandStack.top();
					operandStack.pop();
					int o2 = operandStack.top();
					operandStack.pop();
					operandStack.push(o2-o1);
					operatorStack.pop();
					cout<<o1<<"-"<<o2<<endl;
				}
			}
		}
	}
	return operandStack.top();
}

  

posted @ 2011-08-01 01:23  Sw_R  阅读(183)  评论(0编辑  收藏  举报