Read, then store, a prefix expression

烈酒焚心 提交于 2019-12-12 02:49:43

问题


thanks for reading. I really need some help here. I'm faced with a problem that involves me using a recursive method to store a user-input fully marked prefix expression. In this particular instance, numbers are identified with the symbol "n", while symbols and such are just as they are. So, for example, this:

% 18 + 14 / ( 12 – 11 ) – 1183 % 17

Would be input into the command prompt as this:

  • % n18 / n14 - n12 n11 % n1183 n17

Now, here's what I have for the processing of a completely parenthesized, infix, function. I have to create a method using similar fashion (inside of the same file, actually) and then work with it from there. I've already got the print function working, so I'm really just trying to get the storage to work now. Here's the code to read infix expressions:

Expr * readFPInfix(std::istream & infile)
{
    static std::string ops("*+/%-");
    char symbol;
    infile >> symbol;
    if (symbol == 'n')
    {
        long number;
        infile >> number;
        return new Atom(number);
    }
    else if (symbol == '(')
    {
        Expr * left = readFPInfix(infile);
        char op;
        infile >> op;
        if (ops.find(op) == std::string::npos) {
            std::cout << "Unknown operator symbol '" << op << "'" << std::endl;
            system("pause");
            exit(0);
        }
        Expr * right = readFPInfix(infile);
        infile >> symbol;
        // read the ending right parenthesis
        if (symbol != ')') {
            std::cout << "Invalid symbol '" << symbol << "':  ')' expected" << std::endl;
            system("pause");
            exit(0);
        }
        switch (op)
        {
        case '*':
            return new Times(left, right);
        case '+':
            return new Plus(left, right);
        case '/':
            return new Divide(left, right);
        case '%':
            return new Mod(left, right);
        case '-':
            return new Subtract(left, right);
        default:
            std::cout << "Read error" << std::endl;
            system("pause");
            exit(0);
        }
    }
    else
    {
        std::cout << "Invalid symbol '" << symbol << "':  'n' or '(' expected" << std::endl;
        system("pause");
        exit(0);
    }
}

Now, I'm assuming we have to use the same stuff, so my main problem is reading the damned expression. I understand that in this method we're reading it symbol by symbol, then testing that symbol against prompts to test whether it's an operator or a number. Alright, cool. But how do I get left and right, so I can input it into something like Plus(left, right). I'm really struggling, so any help would be very appreciated.

来源:https://stackoverflow.com/questions/33513749/read-then-store-a-prefix-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!