Home > other >  Expression evaluation from infix to postfix
Expression evaluation from infix to postfix

Time:11-18

#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

CodePudding user response:

The problems is that you don't pop values from the stack. Or at least you don't use the values form the stack, which you pop only once and not twice.

Instead you get the values from the string, so the values of op1 and op2 are the encoded values of the operator you work on.

You need to get the values from the stack:

float op2 = stk.top();
stk.pop();
float op1 = stk.top();
stk.pop();

CodePudding user response:

        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.

  • Related