Question

Using stacks, write an infix expression parser. Here are a few examples of expressions your program should parse and evaluate

Here is the code I have so far. I'm trying to figure out how to implement a boolean and use precedence. The 2nd expression should be 14 but it comes out as 28 so I'm definitely not understanding.

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

using namespace std;

// Function to find precedence of

// operators.

int precedence(char op) {

   if (op == '+' || op == '-')

       return 1;

   if (op == '*' || op == '/')

       return 2;
   //if (op == '^' || op == '')
   return 0;

}


// Function to perform arithmetic operations.

int applyOp(int a, int b, char op) {

   switch (op) {

   case '+': return a + b;

   case '-': return a - b;

   case '*': return a * b;

   case '/': return a / b;

   case '^': return a ^ b;

   }

}


// Function that returns value of

// expression after evaluation.

int evaluate(string tokens) {

   int i;


   // stack to store integer values.

   stack <int> values;

   // stack to store operators.

   stack <char> ops;


   for (i = 0; i < tokens.length(); i++) {


       // Current token is a whitespace,

       // skip it.

       if (tokens[i] == ' ')

           continue;


       // Current token is an opening

       // brace, push it to 'ops'

       else if (tokens[i] == '(') {

           ops.push(tokens[i]);

       }


       // Current token is a number, push

       // it to stack for numbers.

       else if (isdigit(tokens[i])) {

           int val = 0;


           // There may be more than one

           // digits in number.

           while (i < tokens.length() &&

               isdigit(tokens[i]))

           {

               val = (val * 10) + (tokens[i] - '0');

               i++;

           }

           values.push(val);

       }

       // Closing brace encountered, solve

       // entire brace.

       else if (tokens[i] == ')')
       {
           while (!ops.empty() && ops.top() != '(')
           {
               int val2 = values.top();
               values.pop();

               int val1 = values.top();
               values.pop();


               char op = ops.top();
               ops.pop();

               values.push(applyOp(val1, val2, op));
           }

           // pop opening brace.
           ops.pop();
       }

       // Current token is an operator.

       else
       {
           // While top of 'ops' has same or greater

           // precedence to current token, which

           // is an operator. Apply operator on top

           // of 'ops' to top two elements in values stack.

           while (!ops.empty() && precedence(ops.top())
               >= precedence(tokens[i])) {

               int val2 = values.top();
               values.pop();

               int val1 = values.top();
               values.pop();

               char op = ops.top();
               ops.pop();

               values.push(applyOp(val1, val2, op));
           }

           // Push current token to 'ops'.

           ops.push(tokens[i]);
       }
   }


   // Entire expression has been parsed at this

   // point, apply remaining ops to remaining

   // values.

   while (!ops.empty()) {

       int val2 = values.top();
       values.pop();


       int val1 = values.top();
       values.pop();


       char op = ops.top();
       ops.pop();


       values.push(applyOp(val1, val2, op));
   }

   // Top of 'values' contains result, return it.

   return values.top();

}

int main() {

   cout << evaluate("1 + 2 * 3") << "\n";

   cout << evaluate("2 + 2 ^ 2 * 12") << "\n";

   //cout << evaluate("1 == 2") << "\n";

   //cout << evaluate("1 + 3 > 2") << "\n";
  
   //cout << evaluate("(4 >= 4) && 0") << "\n";

   //cout << evaluate("(1 + 2) * 3") << "\n";

   //cout << evaluate("++++ 2 - 5 * (3 ^ 2)");

   return 0;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <bits/stdc++.h>

using namespace std;

  

// Function for finding precedence of

// operators.

int prec(char op){

    if(op == '*'||op == '/')

    return 2;

    if(op == '+'||op == '-')

    return 1;

    return 0;

}

  

// Function used for performing arithmetic operations.

int applyOperation(int a, int b, char op){

    switch(op){

        case '+': return a + b;

        case '-': return a - b;

        case '*': return a * b;

        case '/': return a / b;

    }

}

  

// Function that returns value of

// expression after evaluation.

int eval(string expr){

    int i;

      

    // using a stack to store values(integer).

    stack <int> values;

      

    // stack for storing operators.

    stack <char> ops;

      

    for(i = 0; i < expr.length(); i++){

          

        // Current is a whitespace,

        // skip it.

        if(expr[i] == ' ')

            continue;

          

        // Current character is an opening

        // brace, push it to stack ops that stores operators

        else if(expr[i] == '('){

            ops.push(expr[i]);

        }

          

        // Current character is a number, push

        // it to stack for numbers.

        else if(isdigit(expr[i])){

            int val = 0;

              

            // if more than one digit in one number

            .

            while(i < expr.length() &&

                        isdigit(expr[i]))

            {

                val = (val*10) + (expr[i]-'0');

                i++;

            }

              

            values.push(val);

        }

          

        // Closing brace encountered,now solve the full equation

        else if(expr[i] == ')')

        {

            while(!ops.empty() && ops.top() != '(')

            {

                int val2 = values.top();

                values.pop();

                  

                int val1 = values.top();

                values.pop();

                  

                char op = ops.top();

                ops.pop();

                  

                values.push(applyOp(val1, val2, op));//basically after

//performing the whole operation we push the result onto the stack

            }

              

            // pop opening brace.

            ops.pop();

        }

          

        // Current character is an operator.

        else

        {

            // While top of 'ops' has same or greater

            // precedence to current , which

            // is an operator. Apply operator on top

            // of 'ops' to top two elements in values stack.

            while(!ops.empty() && precedence(ops.top())

                                >= precedence(expr[i])){

                int val2 = values.top();

                values.pop();

                  

                int val1 = values.top();

                values.pop();

                  

                char op = ops.top();

                ops.pop();

                  

                values.push(applyOp(val1, val2, op));

            }

              

            // Push current character to 'ops'.

            ops.push(expr[i]);

        }

    }

      

    // Entire expression has been parsed at this

    // point, apply remaining ops to remaining

    // values.

    while(!ops.empty()){

        int val2 = values.top();

        values.pop();

                  

        int val1 = values.top();

        values.pop();

                  

        char op = ops.top();

        ops.pop();

                  

        values.push(applyOp(val1, val2, op));

    }

      

    // Top of 'values' contains result, return it.

    return values.top();

}

  

Add a comment
Know the answer?
Add Answer to:
Here is the code I have so far. I'm trying to figure out how to implement...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hello, please correct the following C++ CODE it is not working on visual studio: (I WILL RATE, NO...

    Hello, please correct the following C++ CODE it is not working on visual studio: (I WILL RATE, NO INCOMPLETE OR WRONG SOLUTIONS PLEASE) // CPP program to evaluate a given // expression where tokens are // separated by space. #include using namespace std; // Function to find precedence of // operators. int precedence(char op){ if(op == '+'||op == '-') return 1; if(op == '*'||op == '/') return 2; return 0; } // Function to perform arithmetic operations. int applyOp(int a,...

  • The code below accepts and evaluates an integer expression with the following operators: +, _, *,...

    The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements. import java.util.Stack; public class EvaluateExpression { public static void main(String[] args) {     // Check number of arguments passed     if (args.length != 1) {       System.out.println(         "Usage:...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • i want similar for this code to solve two questions : 1- Write a program to...

    i want similar for this code to solve two questions : 1- Write a program to convert a postfix expression to infix expression 2-Write a program to convert an infix expression to prefix expression each question in separate code ( so will be two codes ) #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c;...

  • I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...

    I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ____________________________________________________________________________________________ C++ Program: #include <iostream> #include <string> #include <stdio.h> #include <math.h> using namespace std; //Stack class class STACK { private: char *str; int N; public: //Constructor STACK(int maxN) { str = new char[maxN]; N = -1; } //Function that checks for empty int empty() { return (N == -1); } //Push...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • I'm having trouble writing this code, can some help me? Step 1: Capturing the input The...

    I'm having trouble writing this code, can some help me? Step 1: Capturing the input The first step is to write a functionGetInput()that inputs the expression from the keyboard and returns the tokens---the operands and operators---in a queue. You must write this function. To make the input easier to process, the operands and operators will be separated by one or more spaces, and the expression will be followed by #. For example, here’s a valid input to your program: 6...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT