The conversion between the infix and posfixo formats can be done through the shunting algorithm-Yard.
To understand it, consider that each operator has both a precedence how much a associativity: apply first, for example, and both associate to the left. A - B - C
applies as (A - B) - C
and not as A - (B - C)
, but A^B^C
applies as A^(B^C)
and not the other way around. Subexpressions in parentheses apply before the rest.
The algorithm works by reading each token (number, operator, open parenthesis or close parenthesis) of the input and then placing it either on the output or in a stack. Numbers always go to the output. Operators go to the stack, but before they remove from the stack (sending to the output) any operator whose precedence is less or less-or-equal to it (depending on the associativity). Open parentheses go to the stack, and close parentheses demycle everything until the corresponding parentheses open and play in the output.
1 + 2 * 3 []
_ + 2 * 3 [] 1
_ 2 * 3 [+] 1
_ * 3 [+] 1 2
_ 3 [+, *] 1 2
_ [+, *] 1 2 3
[+] 1 2 3 *
[] 1 2 3 * +
(1 + 2) * 3 []
_1 + 2) * 3 [(]
_ + 2) * 3 [(] 1
_ 2) * 3 [(, +] 1
_) * 3 [(, +] 1 2
_ * 3 [] 1 2 +
_ 3 [*] 1 2 +
_ [*] 1 2 + 3
[] 1 2 + 3 *
1 + 2*3 / (4 ^ (5+6) ) []
_ + 2*3 / (4 ^ (5+6) ) [] 1
_ 2*3 / (4 ^ (5+6) ) [+] 1
_*3 / (4 ^ (5+6) ) [+] 1 2
_3 / (4 ^ (5+6) ) [+, *] 1 2
_ / (4 ^ (5+6) ) [+, *] 1 2 3
_ (4 ^ (5+6) ) [+, /] 1 2 3 *
_4 ^ (5+6) ) [+, /, (] 1 2 3 *
_ ^ (5+6) ) [+, /, (] 1 2 3 * 4
_ (5+6) ) [+, /, (, ^] 1 2 3 * 4
_5+6) ) [+, /, (, ^, (] 1 2 3 * 4
_+6) ) [+, /, (, ^, (] 1 2 3 * 4 5
_6) ) [+, /, (, ^, (, +] 1 2 3 * 4 5
_) ) [+, /, (, ^, (, +] 1 2 3 * 4 5 6
_ ) [+, /, (, ^] 1 2 3 * 4 5 6 +
_ [+, /] 1 2 3 * 4 5 6 + ^
[+] 1 2 3 * 4 5 6 + ^ /
[] 1 2 3 * 4 5 6 + ^ / +
Example in C in rosettacode.
Only with this information can not help. In addition to further detail your code, put what you have already done, what you tried. But I can tell you right now you’re gonna have to create a parser, which is not something trivial.
– Maniero
What is the complexity of this expression? I imagine it has at least addition, subtraction, multiplication and division, and what else? Parentheses? Other functions? Etc. A while ago I I answered a similar question, but in Javascript, not in C. I suggest taking a look there, maybe give a help.
– mgibsonbr
@bigown For the case of arithmetic expressions it may not be necessary to go so far as to create a parser - the conversion of the expression to Reverse Polish notation (post-fixed or postfixed) and subsequent assessment may be sufficient.
– mgibsonbr
@mgibsonbr It would not be a parser, albeit simplified?
– Maniero
@mustache Indeed. On my head a syntax-driven translation was something different - simpler - than what we usually mean by Parsing (whose output is usually an abstract representation of the data). But you’re right, even this is still a parser.
– mgibsonbr
Maybe a val help you.
– DaviAragao
Or maybe this question.
– DaviAragao