📄 d_infixtopostfix.cpp
字号:
#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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -