[comp.lang.c] Character arrays

srn@ulysses.att.com (Shirish R Nadkarni) (07/03/90)

Does anyone have a piece of code that can scan a formula ? I will
try to explain that a bit:

Suppose I have 4 numbers (these will be stored in variable names, but
for the time we will assume that they are stored under 1, 2, 3 and 4).
I need to calculate 

total = 1 * 2 + 3 * 4  OR (1*2) + 3 + 4   OR 1 + (2/3) +4

(these are examples and all the formulas above are obviously not
equivalent)

The input would be in the form of a character array that would be
the right side of the above equation. There may be parentheses present.
(In fact +,-,*,/, (, and ) are legal characters. It can be assumed that
the variables are 1, 2, 3, and 4)
Also blanks may not always be there. I am using 'scanf' to fetch the
input and store that into an array. My job is to 'interpret' the formula
and then process the corresponding variables accordingly to obtain
'total'.

P.S.: the maximum number of variables will be 10.
Thanks in advance

-Shirish (ulysses!srn or srn@ulysses.att.com)

dankg@volcano.Berkeley.EDU (Dan KoGai) (07/05/90)

In article <13281@ulysses.att.com> srn@ulysses.att.com (Shirish R Nadkarni) writes:
>Does anyone have a piece of code that can scan a formula ? I will
>try to explain that a bit:
>
>Suppose I have 4 numbers (these will be stored in variable names, but
>for the time we will assume that they are stored under 1, 2, 3 and 4).
>I need to calculate 
>
>total = 1 * 2 + 3 * 4  OR (1*2) + 3 + 4   OR 1 + (2/3) +4

	Take a look at the source of expr:  expr is a unix utility that
does exactly what you want:  You give formula as an arguments, which
symobols and numbers separated with space.
	I had to do if from scratch in my CS cource.  Maybe it's a good
practice if you do it by yourself.  It was quite benefitial for me.  But
precedence handling was pain in the neck...

----------------
____  __  __    + Dan The "expr 1 / 0" Man
    ||__||__|   + E-mail:       dankg@ocf.berkeley.edu
____| ______    + Voice:        +1 415-549-6111
|     |__|__|   + USnail:       1730 Laloma Berkeley, CA 94709 U.S.A
|___  |__|__|   + Oxymorons:    Usable MS-DOS is oxymoron.
    |____|____  +               Multitasking Mac is oxymoron.
  \_|    |      +               Secure Unix is oxymoron