请写一个中缀表达式转后缀表达式的代码,要求满足四则运算和取余运算
时间: 2023-03-31 14:04:29 浏览: 70
以下是中缀表达式转后缀表达式的代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else if (op == '%') {
return 3;
} else {
return ;
}
}
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (int i = ; i < infix.length(); i++) {
char c = infix[i];
if (isdigit(c)) {
postfix += c;
} else if (c == '(') {
s.push(c);
} else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
} else {
while (!s.empty() && priority(c) <= priority(s.top())) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix = "3+4*5%(6-2)";
string postfix = infixToPostfix(infix);
cout << postfix << endl;
return ;
}
输出结果为:345*62-/+%