Answer to Question #239033 in C++ for Ali

Question #239033
Implement 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;
Write complete code
1
Expert's answer
2021-09-18T15:36:40-0400
// Postfix Evaluator in C++
#include <stack>
#include <iostream>
#include <string>


using namespace std;
 


int evaluate_postfix_from_cin( )
{
    
    stack<int> s;
 	cout<<"Enter a valid postfix expression\n";
	
	string expression;
	cin>>expression;
    
    for (char ch: expression)
    {
        
        if (ch >= '0' && ch <= '9') {
            s.push(ch - '0');
        }
        
        else {
            
            int first_operand = s.top(); //First Operand
            s.pop();
 
            int second_operand = s.top(); //Second Operand
            s.pop();
 
            
            if (ch == '+') {
                s.push(second_operand + first_operand);
            }
            else if (ch == '-') {
                s.push(second_operand - first_operand);
            }
            else if (ch == '*') {
                s.push(second_operand * first_operand);
            }
            else if (ch == '/') {
                s.push(second_operand / first_operand);
            }
        }
    }
 
   
    return s.top();
}
 
int main()
{
    


 
    cout << evaluate_postfix_from_cin();
 
    return 0;
}



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