Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

RPN Calculator but making variables work in C++ I have this already: #include #include #include using namespace std; bool is_number(string s) { for(int i =

RPN Calculator but making variables work in C++

I have this already:

#include #include #include

using namespace std;

bool is_number(string s) { for(int i = 0; i < s.length(); i += 1) if(s[i] < '0' || s[i] > '9') return false; return true; }

int string_to_int(string s) { int sofar = 0; for(int i = 0; i < s.length(); i += 1) sofar = 10 * sofar + s[i] - '0'; return sofar; }

void evalRPN() { vector v; while(true) { string s; cin >> s; if(is_number(s)) v.push_back(string_to_int(s)); else if(s == "+" || s == "-" || s == "*" || s == "/") { int b = v.back(); v.pop_back(); int a = v.back(); v.pop_back(); if(s == "+") v.push_back(a + b); else if(s == "-") v.push_back(a - b); else if (s == "*") v.push_back(a * b); else if (s == "/") { if(b == 0) { cout << "Division by zero! "; v.push_back(0); } else v.push_back(a / b); } } else if(s == "end") { cout << "Result is: " << v.back() << " "; v.clear(); } else if(s == "exit") { cout << "Goodbye "; exit(0); } else cout << "Invalid item: " << s << " "; } }

int main() { cout << " Enter a number or operator, then press enter. " << "Type \"end\" to finish and get your result. " << "To close the program, type \"exit\". ";

evalRPN(); }

However i need to make it work with variables, for example:

If the input is 2 3 4 + * = a end that means work out 2*(3+4) and remember that as the value of a. = needs to be handled specially, don't treat it as a normal operator If the input is 2 a * end then the result should be whatever 2 * a is

Thank you!

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions