d_infixtopostfix.cpp

来自「后辍表达式的计算」· C++ 代码 · 共 109 行

CPP
109
字号
#include "d_infixToPostfix.h"

infixToPostfix::infixToPostfix()
{
}

infixToPostfix::infixToPostfix(const string& infix)
{ infixExpression=infix;
}


void infixToPostfix::setInfix(const string& infix)
{ infixExpression=infix;
  postfixExpression="";
  while(!commandStack.empty()) commandStack.pop();

}

bool infixToPostfix::isCommand(char ch) const
{
	return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}

void infixToPostfix::outputCommand(const instruction &instr)
{   instruction instr1;
	while(!commandStack.empty()&&((instr1=commandStack.top())>=instr)){
	postfixExpression+=instr1.getCommand();
	postfixExpression+=" ";
	commandStack.pop();
	}
}






string infixToPostfix::postfix()
{ int times=0;
  
	for(unsigned int i=0;i<infixExpression.length();i++)
	{   
		char ch=infixExpression[i];
		if(isdigit(ch)){
			postfixExpression+=ch;
			postfixExpression+=" ";
			times++;
			if(times>1) 
				throw
				    expression_error("infixToPostfix:算式错误,缺少算术符!");
		}
		else if(isCommand(ch)){
			times--;
			if(times<0)
				throw
				expression_error("infixToPostfix:算式错误,缺少操作数!");
			else{
                   instruction instr(ch);
				   outputCommand(instr);
				   commandStack.push(instr);
			}
		}

		else if(ch=='('){
			if(times<0)
				throw expression_error("infixToPostExpression:缺少操作数");
			else{
			instruction instr(ch);
			outputCommand(instr);
		    commandStack.push(instr);
			}
		}

		else if(ch==')'){
			instruction instr(ch);
			outputCommand(instr);
			if(commandStack.empty())
				throw expression_error("infixToPostfix:缺少 '('");
			 else commandStack.pop();
		}

		else if(!isspace(ch))
			throw expression_error("infixToPostfix:非法输入!");
	}

	if(times!=1)
		throw expression_error("infixToPostfix:错误输入,缺少操作数!");
	else{
		while(!commandStack.empty()){
			instruction instr=commandStack.top();
			commandStack.pop();
			if(instr.getCommand()=='(')
				throw expression_error("infixToPostfix:缺少 ')'");
			else{
				postfixExpression+=instr.getCommand();
				postfixExpression+=" ";
			}
		}
	}
	return postfixExpression;
}



  



⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?