fork download
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. int precedence(char op) {
  8. if (op == '+' || op == '-')
  9. return 1;
  10. if (op == '*' || op == '/')
  11. return 2;
  12. return 0;
  13. }
  14.  
  15. string infixToPostfix(const string& infix) {
  16. string postfix;
  17. stack<char> operators;
  18.  
  19. for (char c : infix) {
  20. if (isalnum(c)) {
  21. postfix += c;
  22. } else if (c == '(') {
  23. operators.push(c);
  24. } else if (c == ')') {
  25. while (!operators.empty() && operators.top() != '(') {
  26. postfix += operators.top();
  27. operators.pop();
  28. }
  29. if (!operators.empty() && operators.top() == '(')
  30. operators.pop();
  31. } else {
  32. while (!operators.empty() && precedence(operators.top()) >= precedence(c)) {
  33. postfix += operators.top();
  34. operators.pop();
  35. }
  36. operators.push(c);
  37. }
  38. }
  39.  
  40. while (!operators.empty()) {
  41. postfix += operators.top();
  42. operators.pop();
  43. }
  44.  
  45. return postfix;
  46. }
  47.  
  48. int main() {
  49. string infix_expression;
  50. cout << "Enter infix expression: ";
  51. getline(cin, infix_expression);
  52.  
  53. string postfix_expression = infixToPostfix(infix_expression);
  54. cout << "Postfix expression: " << postfix_expression << endl;
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
Enter infix expression: Postfix expression: