Question

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 4 15 * – #

Back in Codio, modify “main.cpp” by defining the following function above main(). Note the additional #include statements, add those as well:

#include <iostream>

#include <stack>

#include <queue>

#include <string>

#include <sstream>

#include <cctype>

using namespace std;

queue<string> GetInput()

{

queue<string> Q;

stringtoken;

cin >> token;

.. // TODO: loop andinputrestof expression, adding to queue. // Do not add the sentinel # to the queue..

return Q;

}

Now modify the main() function to call GetInput, and change the cout statement to output the size of the queue returned by GetInput. This is a simple check to make sure the queue contains the elements of the expression. Build and run, and enter an expression such as

6 4 15 * – #

The output should be a size of 5---3 operands and 2 operators (the # should not be stored in the queue). If you want to be sure the queue is correct, write a quick loop to pop the contents of the queue one by one, and output. When you’re done, comment out these debug output statements.

Step 2: Evaluating the expression (assuming valid input)

Now that the input has been captured, step 2 is to evaluate the expression. The idea is simple: when you see an operand (an integer), push it on a stack. When you see an operator, pop off two operands, perform the operation, and push on the result. When the input has been processed, the answer is on top of the stack. Go ahead and draw out an example on paper and convince yourself it works: 6 4 15 * - should yield -54.

Write a function EvaluatePostfix that takes a queue containing the input, and returns two values: the integer result, and true / false(denoting valid input or not). Here’s the function definition:

bool EvaluatePostfix(queue<string> input, int& result)

{

stack<int> operands;

.. // evaluate expression:.

result = operands.top(); // answer is on top

return true; // successful evaluation

}

For now, assume valid input, and don’t bother with error checking.Loop until the queue is empty, popping one token at a time. Since the tokens are strings, and a string is an array of characters, you can access the first element of a string using[0]. This makes it easy to tell if a token is an integer operand:

string s = input.front();// next token in the queue:

input.pop();

if (isdigit(s[0]))// integer operand:

{

operands.push(stoi(s));// in C++, usestoito convert string to int

}

else // operator{

...

}

To determine the operator, compare s[0] to ‘+’, ‘*’, etc. Once you have the function written, modify main() to call the function and output the result. Build, run and test with a variety of expressions. Here’s a few:

6 4 15 * – # => -54

6 4 –5 * # => 10

21 10 30 * + 80 / # => 4

Step 3: Handling invalid input

The last step is to extend the program to handle invalid input. Modify the EvaluatePostfix function to handle the following:

1. What if the stack contains more than one value at the end (or is empty)? This can happen when the input is empty, or the expression doesn’t contain enough operators. Example: 1 2 3 + #. In this case EvaluatePostfix should return false.

2. What if the stack does not contain 2 operands when an operator is encountered? This can happen when the expression doesn’t contain enough operands. Example: 1 2 + + #. In this case EvaluatePostfix should return false.

3. What if the operator is something other than +,-, * or /. In that case, EvaluatePostfix should return false.

You’ll need to modify main() to check the value returned by EvaluatePostfix. If false is returned, output the word “invalid” followed by a newline. Build, run and test.

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

#include <iostream>

#include <stack>

#include <queue>

#include <string>

#include <sstream>

#include <cctype>

using namespace std;

queue<string> GetInput()

{

queue<string> Q;

stringtoken;

cin >> token;

.. // TODO: loop andinputrestof expression, adding to queue. // Do not add the sentinel # to the queue..

return Q;

}

bool EvaluatePostfix(queue<string> input, int& result)

{

stack<int> operands;

.. // evaluate expression:.

result = operands.top(); // answer is on top

return true; // successful evaluation

}

For now, assume valid input, and don’t bother with error checking.Loop until the queue is empty, popping one token at a time. Since the tokens are strings, and a string is an array of characters, you can access the first element of a string using[0]. This makes it easy to tell if a token is an integer operand:

string s = input.front();// next token in the queue:

input.pop();

if (isdigit(s[0]))// integer operand:

{

operands.push(stoi(s));// in C++, usestoito convert string to int

}

else // operator{

...

}

Add a comment
Know the answer?
Add Answer to:
I'm having trouble writing this code, can some help me? Step 1: Capturing the input The...
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
  • 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:...

  • Here is the code I have so far. I'm trying to figure out how to implement...

    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 ==...

  • 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...

  • 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...

  • I NEED SAMPLE PRINT OUT AS WELL AS CODE PLEASE!!!! Objectives: To gain experience with stacks....

    I NEED SAMPLE PRINT OUT AS WELL AS CODE PLEASE!!!! Objectives: To gain experience with stacks. Documentation: Explain the purpose of the program as detail as possible - 8%. Develop a solution for the problem and mention algorithms to be used -12% List data structures to be used in solution. - 5%. Give a description of how to use the program and expected input/output - 5% Explain the purpose of each class you develop in the program. - 5%. Programming:...

  • You are to write a program that implements a Reverse Polish Notation Calculator in C using...

    You are to write a program that implements a Reverse Polish Notation Calculator in C using BISON and FLEX, You only have to edit the BISON and FLEX files. Link to the files to start and have a general view of the program: https://www.dropbox.com/sh/83yzs66jhftqj5b/AABZcY9Qwl84JdUFnYpQaZk9a?dl=0 Reverse Polish Notation is a mathematical notation in which every operator follows all of its operands. It is sometimes called postfix notation, and does not require any parentheses as long as each operator has a fixed...

  • 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...

  • 1. Specification Write a C program to implement a simple calculator that accepts input in the...

    1. Specification Write a C program to implement a simple calculator that accepts input in the following format and displays the result of the computation: calc [operand_1] [operator] [operand_2] The operands operand_1 and operand_2 are non-negative integers. The operator is one of the following: addition (+), subtraction (-), multiplication (x), division (/) and modulo (%). Note: For the multiplication operator, use letter ‘x’. If you use the asterisk ‘*’, your program will not work properly 2. Implementation • The program...

  • You are to write a program name expressionTree.java that evaluates an infix expression entered by the...

    You are to write a program name expressionTree.java that evaluates an infix expression entered by the user. The expression may contain the following tokens: (1) Integer constants (a series of decimal digits). (2)   One alphabetic character - "x" (representing a value to be supplied later). (3)   Binary operators (+, -, *, / and % (modulo)). (4)   Parentheses          You will parse the input expression creating an expression tree with the tokens, then use the postOrder tree traversal algorithm to extract...

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