I think you're essentially going to need a parser. Because you're going to have to make decisions like which operators bind more tightly than the others.
I may be missing a simple and elegant solution though.
cja
2009-06-03 13:18:53 UTC
Limiting expressions to just binary arithmetical operations and not allowing parentheses helps keep this simple. By using two vectors, as you're talking about above, I think you're making it more difficult, complicating expression validation and evaluation.
My idea is to put operands and operators together in a single vector. This way you can evaluate "x op y", store the result in the vector where the operator was, remove the operands, evaulate the next "x op y", and so on until the vector contains only the final result. (Keeping operator precedence in mind, of course.) This evaluation assumes a properly formed expression; input validation is required so you won't attempt to evaulate a malformed expression.
So, see below for how I would do it. I hope it gives you some ideas of how to get your program working.
#include
#include
HandyManOrNot
2009-06-02 21:58:42 UTC
The key is your vector of ops.Since you are using only +-*/, you just start through the ops vector and first look for the * and / characters. Each time you find one, you use its vector index to access the surrounding two numbers in the int vector. Using ASCII character matching, determine which operation to perform, update one of the int vectors with the new value and eliminate the other, then eliminate the op vector. Once all the * and / ops are gone, do the same for the + and - ops.
This code is a little too complex to simply post, hopefully you have a working vector with update and remove functions, and know how to loop through the vectors and keep track of position.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.