Flipke said:
I wanna make a calculator where i can give the input in one word. for
example : (15*3) / (2+3)
I think i most read this in as a string and then share it in different
parts
to do the calculation. But i don't now how tho start with it. Can somebody
help me.
To write a parser, firstly many of the rules of good programming don't apply
to parsers.
Normally the caller should ensure that the input is valid. For a parser, the
caller cannot do this without without writing another parser himself. So you
have to be very careful about handling errors.
Normally you should not have mutually recursive functions. For a parser,
this structure is natural.
Normally you should not have global variables. A parser is one place where
code is often neater if you do use globals.
How do you do it? The basic principle is that when you hit a bracket, you
call the top-level function on the contents. This is why parsers are
mutually recursive.
Arithmetical expressions have the bodmas (brackets, of, divide, multiply,
add, subtract) rule.
What you want to do is declare a global pointer to input so far. Then you
write a function called gettoken() which returns the token (number,
operator, parentheses) in the input stream, but does not remove it. Then
write a function called match() which discards the token from the stream,
but only if it is of the type passed. Otherwise it flags an error.
Then write three functions, expression(), term() and factor(). A factor is
either a raw number or an open parenthesis containing an expression
(recursion). A term is either a raw factor, or a series of factos connected
by divides and multiplies. An expression is either a raw term, or a series
of terms connected by additions and subtractions.
Once you have all this working, you basically have your calculator. It is
quite hard, so post your attempt if you get stuck.