Answer to Question #235781 in C++ for Johnson

Question #235781
mplement the following function. You may use the stack template class and the
stack operations of push, pop, peek, is_empty, and size. You may also use cin.peek( )
and use "cin>>i" to read an integer.
int evaluate_postfix_from_cin( )
// Precondition (Which is not checked): The next input line of cin is a
// properly formed postfix expression consisting of integers,
// the binary operations + and -, and spaces.
// Postcondition: The function has read the next input line (including
// the newline) and returned the value of the postfix expression.
{
int i;
stack<int> s;
1
Expert's answer
2021-09-10T18:51:22-0400
int evaluate_postfix_from_cin(char* e)
{
    struct Stack* s = createStack(strlen(e));
    int i;
    if (!s) return -1;
    for (i = 0; e[i]; ++i)
    {
        if (isdigit(e[i]))
            push(s, e[i] - '0');
        else
        {
            int v1 = pop(s);
            int v2 = pop(s);
            switch (e[i])
            {
            case '+': 
                push(s, v2 + v1); 
                break;
            case '-': 
                push(s, v2 - v1); 
                break;
            case '*': 
                push(s, v2 * v1); 
                break;
            case '/': 
                push(s, v2/v1); 
                break;
            }
        }
    }
    return pop(s);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS