#include <iostream>
#include <string>
#include <stack>
using namespace std;
float postix_evalute(string expr)
{
stack<float> stk;
float val;
for (int x = 0; x < expr.length(); x++)
{
if (isdigit(expr[x]))
{
stk.push((expr[x] - '0'));
}
else
{
float op2 = expr[x];
stk.pop();
float op1 = expr[x];
stk.top();
switch (expr[x])
{
case '+':
val = op1 + op2;
break;
case '-':
val = op1 - op2;
break;
case '*':
val = op1 * op2;
break;
case '/':
val = op1 / op2;
break;
}
stk.push(val);
}
}
return stk.top();
}
int main()
{
string line;
cout << "The Value Of experssion" << endl;
cin >> line;
cout << postix_evalute(line) << endl;
return 0;
}
This code to get postfix-evalue for string which user enter put when i try to run this code it give me random value not give me the right answer so i want to know what is the problem for example when i enter 32+ it give me 86
if (isdigit(expr[x]))
{
stk.push((expr[x] - '0'));
}
You're pushing individual digits one at a time. If you run postfix_evaluate("32")
, this loop will push 3
onto the stack first, and then 2
. Are you sure you don't want the single value 32
on the stack instead?
You can, and should, debug this basic stuff before you write lots of code on a wobbly foundation.
float op2 = expr[x];
stk.pop();
These lines copy a single character from the string (which we've just decided is not a digit), promote it to a float
, and then discard the top of the stack without examining it at all.
For example, if the char is '+'
(and your encoding is ASCII), you'll have op2 = 43.0
. You have the same problem with op1
.