c++data-structuresexpressionpostfix-notation

Evaluate multi digit expression


I wrote this code to evaluate postfix expressions, but in this code I can only evaluate an expression with only single-digit numbers. I want to edit this code for it to evaluate multi-digit numbers. How can I do this?

#include <iostream>
#include <stack>
#include <string>

using namespace std;

float calc(float o1,float o2,char c)
{
    if(c=='+') return o1+o2;
    if(c=='-') return o1-o2;
    if(c=='*') return o1*o2;
    if(c=='/') return o1/o2;
    else return 0;
}

float evaluate(string exp)
{
    float result=0;
    stack<char>s;
    for(int i=0;i<exp.length();i++)
    {
         if(isdigit(exp[i]))
        {

             s.push(exp[i]-'0');
        }
        else
        {
            float o2=s.top();
            s.pop();
            float o1=s.top();
            s.pop();
             result = calc(o1,o2,exp[i]);
            s.push(result);

        }
    }
    return s.top();
}

int main()
{
    string exp="382/+5-";
    cout<<evaluate(exp);
    return 0;
}

Solution

  • For multi-digit numbers, you need a separator symbol eg. space. All the tokens in postfix will be space separated. You need to read one token at a time. For example, expression "28 2 / 5 -" can be evaluated as follows:

    #include <iostream>
    #include <stack>
    #include <string>
    
    using namespace std;
    
    float calc(float o1,float o2,char c)
    {
        if(c=='+') return o1+o2;
        if(c=='-') return o1-o2;
        if(c=='*') return o1*o2;
        if(c=='/') return o1/o2;
        else return 0;
    }
    
    float evaluate(string exp)
    {
        float result=0;
        stack<int> s ;
        int dig = 0;
        int i=0;
        while(i<exp.length())
        {
            char e = exp[i];
            if(isdigit(exp[i])) {
                dig = dig*10 + (exp[i]-'0');
            } else if (exp[i] == ' ') {
                s.push(dig);
                dig = 0; 
            } else {
                float o2=s.top();
                s.pop();
                float o1=s.top();
                s.pop();
                result = calc(o1,o2,e);
                s.push(result);
                i++;
    
            }i++;
        }
        return s.top();
    }
    
    int main()
    {
        string exp="28 2 / 5 -";
        cout<<evaluate(exp);
        return 0;
    }
    

    additional ref link:Postfix evaluation for multidigit numbers