Similar question has been asked here, However, still remains unanswered (at least no code provided, though the suggestion is good)
My code unlike the hyperlinked one, only evaluates the entered expression I am not being able to fabricate a logic to accept negative numbers. Note that in my code, the expression to be entered has to be in proper postfix format, and the multi-digit numbers have to be surrounded with parenthesis.
Here is my code:
float expression::eval()
{
std::stack<float> s;
float op1, op2;
for (int i = 0; i < expr.length(); i++)
{
if (expr[i] == '(')
{
float sum = 0;
while (expr[++i] != ')')
{
sum = sum * 10.0 + (float(expr[i]) - float('0'));
}
s.push(sum);
continue;
}
else if (!isOperator(expr[i]))
{
s.push(float(expr[i]) - float('0'));
}
else
{
op2 = s.top();
s.pop();
op1 = s.top();
s.pop();
switch (expr[i])
{
case '+':
s.push(op1 + op2);
break;
case '-':
s.push(op1 - op2);
break;
case'*':
s.push(op1*op2);
break;
case '/':
s.push(op1 / op2);
break;
default:
std::cerr << "Wrong operator" << std::endl;
return 0;
}
}
}
return s.top();
}
Note that expression is an object in my code. my class:
class expression
{
//constructors and destructors
public:
expression();
~expression();
//member properties
private:
std::string expr;
//member methods
public:
// accepts the expression from the user
void input();
//prints the accepted expression
void output();
//evaluates the accepted expression
float eval();
//
friend bool isOperator(char);
};
eg:- 12+12*2
needs to be written as
(12)(12)+2*
This is what I tried. But, it doesn't work. Can anyone explain what's wrong in this logic?:
if (expr[i] == '(')
{
float sum = 0;
bool flag = false;
while (expr[++i] != ')')
{
if (expr[i] == '-')
flag = true;
sum = sum * 10.0 + (float(expr[i]) - float('0'));
}
if (flag)
sum = -sum;
s.push(sum);
continue;
}