fork download
  1. #include<bits/stdc++.h>
  2.  
  3. //Evaluating infix expression without converting it into postfix in a single scan
  4.  
  5. int isoperand(char x)
  6. {
  7. if(x == '+' || x=='-'|| x=='*' || x=='/' || x==')' || x=='(')
  8. return 0;
  9. return 1;
  10. }
  11.  
  12. int Pre(char x)
  13. {
  14. if(x == '+' || x == '-')
  15. return 1;
  16. if(x == '*' || x == '/')
  17. return 3;
  18. return 0;
  19. }
  20.  
  21. int postfixevaluation(std::string exp)
  22. {
  23. std::stack<int> operandStack;
  24. std::stack<char> operatorStack;
  25. int i,x,y,z,operand;
  26. i=0;
  27. while(exp[i]!='\0')
  28. {
  29. if(exp[i]==' ' || exp[i]==',')
  30. {
  31. i++;
  32. continue;
  33. }
  34.  
  35. if(isoperand(exp[i]))
  36. {
  37. operand = 0;
  38. while(i<exp.length() && isoperand(exp[i]))
  39. operand = operand*10 + (exp[i++]-'0');
  40. operandStack.push(operand);
  41.  
  42. }
  43. else if(!isoperand(exp[i]) && operatorStack.empty())
  44. operatorStack.push(exp[i++]);
  45. else if(!isoperand(exp[i]) && !operatorStack.empty())
  46. {
  47. if(exp[i]=='(')
  48. operatorStack.push(exp[i++]);
  49. else if(Pre(exp[i])>Pre(operatorStack.top()) && exp[i]!=')')
  50. operatorStack.push(exp[i++]);
  51. else if(exp[i]==')' && operatorStack.top() == '(')
  52. {
  53. operatorStack.pop();
  54. i++;
  55. }
  56.  
  57. else
  58. {
  59. x = operandStack.top();
  60. operandStack.pop();
  61. y = operatorStack.top();
  62. operatorStack.pop();
  63. z = operandStack.top();
  64. operandStack.pop();
  65. if(y == '+')
  66. operandStack.push(z+x);
  67. else if(y == '-')
  68. operandStack.push(z-x);
  69. else if(y == '*')
  70. operandStack.push(x*z);
  71. else if(y == '/')
  72. operandStack.push(z/x);
  73. }
  74. }
  75. }
  76. while(!operatorStack.empty())
  77. {
  78. x = operandStack.top();
  79. operandStack.pop();
  80. y = operatorStack.top();
  81. operatorStack.pop();
  82. z = operandStack.top();
  83. operandStack.pop();
  84. if(y == '+')
  85. operandStack.push(x+z);
  86. else if(y == '-')
  87. operandStack.push(z-x);
  88. else if(y == '*')
  89. operandStack.push(x*z);
  90. else if(y == '/')
  91. operandStack.push(z/x);
  92. }
  93. return operandStack.top();
  94. }
  95.  
  96. int main(int argc, char const *argv[])
  97. {
  98. std::string s;
  99. getline(std::cin,s);
  100. std::cout<<postfixevaluation(s)<<std::endl;
  101. return 0;
  102. }
  103.  
Success #stdin #stdout 0s 4288KB
stdin
3-5*10/5+10
stdout
3