# Formula string conversion

• 04-11-2002
Gr3g
Formula string conversion
Hey,
Im writing a program in which i would like the user to be able to enter a formula then have the formula calculated. The only way i can think of doing this is to have the formula imputted into a string, then use a switch and some loops to execute the formula. Is there a library or a more elegant method to do this?

Thak you,
Gr3g
• 04-12-2002
kmaz
I'm pretty sure there is no simple way to do this, but with classes/objects you would be able to do it probably in a cool way.
• 04-12-2002
Unregistered
have the user enter the expression in postfix

Code:

``` char array[MAX]; char ch; int i=0; while (ch=(char) getc(stdin)){ array[i]=ch; } int pop(int a) { return array[a]; } void push(int b) { array[countvar]=b; }```

the basic idea is this: if the element is a number, pop it from the stack. If it is an operand, then add/sub/mult/divide the two numbers popped from the stack and push the result.

Here is an example: 67+12++ (this is 6+7+1+2)
the program pops 6 and 7, sees the +, adds 6+7, and pushes 13 so the resulting expr is 1312++, which evaluates to 133+, which evaluates to 16.

In reality it is harder, because you will have to deal with conversions. Also, it is nice if you incorporate the whole thing into a struct or class, and make pop and push private functions. That way it is easier to have a countvar that keeps track of where you are in the stack.