|
|
> I also find myself constantly cursing that I have to write an entire 5
> lines of (nearly identical) code for every arithmetic operation I want to
> implement and there's no way to abstract this. (I don't have copy & paste
> available!)
What you could do, is have a function like DoOperation(stack,op), and use
"op" as a token for the operation.
So you would call it like:
if (cmd == "+") {DoOP(stack,0); continue;}
if (cmd == "-") {DoOP(stack,1); continue;}
if (cmd == "/") {DoOP(stack,2); continue;}
if (cmd == "*") {DoOP(stack,3); continue;}
Or you could even use some fancy look-up table to convert from the character
code to op number, or just use the ASCII code of the operator as the op
number... you get the idea.
Then, DoOperation() would look like:
if (!StackCheck(stack, 2)) return;
int x = stack.back(); stack.pop_back();
int y = stack.back(); stack.pop_back();
int answer;
if(op==0) answer=x+y;
if(op==1) answer=x-y;
if(op==2) answer=x/y;
if(op==3) answer=x*y;
stack.push_back(answer);
I'm sure there's a better way of doing it, but I think that's less work than
your first version.
PS good work on the first C++ program, it's way cooler than any of my first
programs.
Post a reply to this message
|
|