我正在编写反向波兰表示法,我的输入应如下所示:<number of chars in expression>" "<expression>
例如。 “ 13(4 * 2)+(5/3)* 5”。但是,当我将该拆分的表达式提供给函数时,将这一个字符串拆分为2个字符串(数字和表达式)后,算法将无法正常工作。
当我仅使用表达式创建字符串并调用函数时,程序正在运行。
int main(){
string exp ="(4*2)+(5/3)*5";
ONP(exp);
return 0;
}
int piority(char d){
if(d == '+' || d == '-') return 1;
if(d == '*' || d == '/' || d == '%') return 2;
if(d == '^') return 3;
return 0;
}
void ONP(string exp){
int i(0); string ans;
stack <char> stos;
while(exp[i] != '\0'){
char d = exp[i];
if((int)exp[i]>47 && (int)exp[i]<58) ans+=d;
if(d == '+' || d == '-' || d == '*' || d == '/' || d == '%' || d == '^' ){
char b = stos.top();
while(piority(d)<=piority(b)){
ans += stos.top();
stos.pop();
b = stos.top();
}
stos.push(d);
}
else if ( d == '(') stos.push(d);
else if( d == ')')
{
while(stos.top() != '('){
ans += stos.top();
stos.pop();
}
if(stos.top() == '(') stos.pop();
}
i++;
}
while(stos.size()>0){
ans+=stos.top();
stos.pop();
}
cout<<endl<<ans;
}
int main(){
string exp ="13 (4*2)+(5/3)*5";
int abc = exp.find(' ');
string exp1 = exp.substr(0,abc);
string exp2 = exp.substr(++abc);
ONP(exp2);
return 0;
}
我想粘贴到命令行表达式中,例如“ 13(4 * 2)+(5/3)* 5”,并输出,例如“ 42 * 53/5 * +”。 / p>