stack<int> s;
int main() {
string exp;
cout << "Enter postfix expression: ";
getline(cin, exp);
int calc = evaluatePosfix(exp);
cout << calc << endl;
}
int evaluatePosfix(string exp) {
for (int i = 0; i < exp.length(); i++) {
if (exp[i] == ' ' || exp[i] == ',') {
continue;
}
if (isNum(exp[i])){
int operand = 0;
while(i < exp.length() && isNum(exp[i])) {
operand = (operand*10) + (exp[i] - '0');
i++;
}
i--;
cout << operand << "&&" << endl;
s.push(operand);
}
else if(isOperator(exp[i])) {
int operand2 = s.top(); s.pop();
int operand1 = s.top(); s.pop();
int result = performOperation(operand1, operand2, exp[i]);
s.push(result);
}
//cout << s.top() << " $$$" << endl;
}
return s.top();
}
bool isOperator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
return true;
}
return false;
}
bool isNum(char c) {
if (c >= '0' || c <= '9') {
return true;
}
return false;
}
int performOperation(int operand1, int operand2, char operation) {
if (operation == '+') {
return operand1 + operand2;
}
else if (operation == '-') {
return operand1 + operand2;
}
else if (operation == '*') {
return operand1 * operand2;
}
else if (operation == '/') {
return operand1 / operand2;
}
else {
cout << "Error" << endl;
return -1;
}
}
Пост-исправление не оценивается должным образом. Когда я набираю 22+, он возвращает 215 вместо 4. Когда программа обнаруживает оператор, она должна выбросить 2 элемента в стек, но по какой-то причине этого не происходит. При вызове executeOperation операция не выполняется, поэтому в стек ничего не помещается.