fork download
  1. #include <iostream>
  2. #include <stack> // don't have time to implement a stack by myself
  3. using namespace std;
  4.  
  5. // function to check precedence
  6. int pre(char op);
  7.  
  8. int main()
  9. {
  10. string infix;
  11. cout << "Expression: ";
  12. cin >> infix;
  13.  
  14. stack<char> st;
  15. string postfix = "";
  16. for (int i = 0; i < infix.length(); i++)
  17. {
  18. char c = infix[i];
  19. if (c >= '0' && c <= '9') // To make sure we are adding any number we meet
  20. postfix += c;
  21.  
  22. else if (c == '(') // open prenthesess are added to our cup
  23. st.push(c);
  24.  
  25. else if (c == ')')
  26. {
  27. // making sure we are poping from not empty stack
  28. while (!st.empty() && st.top() != '(')
  29. {
  30. postfix += st.top();
  31. st.pop();
  32. }
  33. st.pop(); // to remove one '(', aka remove one open prentheesss
  34. }
  35. else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^')
  36. {
  37. while (!st.empty() && pre(st.top()) >= pre(c))
  38. {
  39. postfix += st.top();
  40. st.pop();
  41. }
  42. st.push(c);
  43. }
  44. }
  45. while (!st.empty())
  46. {
  47. postfix += st.top();
  48. st.pop();
  49. }
  50.  
  51. cout << "After Converting To Postfix: " << postfix;
  52.  
  53. return 0;
  54. }
  55.  
  56. // What comes before the other ..uuuh
  57. int pre(char op)
  58. {
  59. if (op == '^')
  60. return 3;
  61. if (op == '*' || op == '/')
  62. return 2;
  63. if (op == '+' || op == '-')
  64. return 1;
  65. return 0;
  66. }
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Expression: After Converting To Postfix: