从超过一位数字的数字中获取后缀表达式的值

get value of postfix experssion from number more than one digit

#include <iostream>
#include <string>
#include <stack>
using namespace std;
float postix_evalute(string expr)
{
    stack<float> stk;

    for (int x = 0; x < expr.length(); x++)
    {
        if (isdigit(expr[x]))
        {
            stk.push((expr[x] - '0'));
        }
        else
        {
            float val;
            float op2 = stk.top();
            stk.pop();
            float op1 = stk.top();
            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 expression" << endl;
    cin >> line;
    cout << postix_evalute(line) << endl;
    return 0;
}

当我输入表达式“213+”时,我得到输出“4”;但我希望得到 24 (21+3).

操作数多于on位怎么办?

您需要一种方法来区分后缀表达式的标记。例如,如果输入是 213+,解析器通常会将其读取为 213+。对于这些简单的表达式,您可以用空格分隔不同的标记,如 21 3 +。然后,将该输入放入字符串中,您可以使用输入字符串流读取每个标记。

float postix_evalute(std::string input)
{
    std::stack<float> stk;

    std::istringstream iss{input};
    std::string token{};
    while (not iss.eof())
    {
        iss >> token;

        try
        {
            stk.push(std::stof(token));
        }
        catch (const std::invalid_argument& ex)
        {
            assert(stk.size() >= 2);
            float op2 = stk.top(); stk.pop();
            float op1 = stk.top(); stk.pop();

            float val{};
            if (token == "+") { val = op1 + op2; }
            else if (token == "-") { val = op1 - op2; }
            else if (token == "*") { val = op1 * op2; }
            else if (token == "/") { val = op1 / op2; }
            else { throw std::runtime_error{std::string{"unknown token: " + token}}; }

            stk.push(val);
        }
    }

    return stk.top();
}

Demo 1: 使用 21 3 + 作为输入。
Demo 2: 使用 21 3 # 作为输入。