Reverse Polish Notation calculator C++ You are to implement a program that promp
ID: 3696255 • Letter: R
Question
Reverse Polish Notation calculator C++
You are to implement a program that prompts for a string in reverse polish notation and calculates it.
YOU DO NOT NEED TO CONVERT FROM A NORMAL EXPRESSION TO REVERSE POLISH.
You should take reverse polish notation and calculate the result of it.
You should allow *, /, +, -, % as operators, which should perform integer division, etc.
To do this, start by reading in a string from the user.DO not use stringstream. Use the string operations to convert from string to integer.
Start by going through this string from left to right. Then:
1)If it is a number, keep going until you get a space, convert that portion of the string to an integer, then push it into a stack. You can convert it using the atoi function.
2)If it an operator, pop the top two elements of the stack, perform the operation, then push that new integer back on the stack. Keep doing this for all the “tokens” (ie: things separated by spaces) in the string.
When you are done evaluating the expression, the result should be on the top of the stack Implementation details: You should implement this in two ways, using a dynamic stack as written in the book and using the STL stack. Your program should start by prompting for a 0 or 1. If they enter a 0, use your own implementation of a stack. If they enter a 1, use an STL stack.
Explanation / Answer
#include // header file io #include // header file for string #include // header file for stack operations #include // header stream #include // standard library using namespace std ; int main() { stackstack; // stack declaration int i; // variable for operations float num,result,first,second; // variable for operations char op,ch; // characters for + - * / string str,str1; //Strings for operatiohs getline(cin,str); // reading line istringstream is(str); for(;is>>str1;){ // loop if(str1.compare("+")==0){ // for addition first=stack.top(); // first operand stack.pop(); second=stack.top(); stack.pop(); // second operand stack.push(first+second); // result push to stack } else if(str1.compare("-")==0) // for - operation { first=stack.top(); stack.pop(); second=stack.top(); stack.pop(); stack.push(first-second); } else if(str1.compare("*")==0) // for multiplication { first=stack.top(); stack.pop(); second=stack.top(); stack.pop(); stack.push(first*second); } else if(str1.compare("/")==0) // for division { first=stack.top(); stack.pop(); second=stack.top(); stack.pop(); stack.push(first/second); } else // except all other cases { stack.push(strtof(str1.c_str(),NULL)); } } coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.