How to read equasion???
Hi there. I been working on some math C++ programs but I can't continue without solving one serious problem. Here it is: How can you convert an array of chars to something compiler could prosses. For examlpe, we recived (50-6)*9+12 from keyboard using cin.getline(). For now it's a bunch of characters. What function(or methood) can tell a compiler to read, understand and SOLVE all this.
Any help would be very userfull. ThanX.
Look up in your favourite texts or help files the functions...
there are a few others too but these are the main ones.
Use stacks. Turn the equation into postfix and then solve using the stack.
Solving an expression as posted is not a trivial endeavor. The common approach is to use the tools as per the other two posts, but how?
First read in the expression. This will be in what's called an infix notation as a string.
First parse the expression into tokens using strtok() or equivalent string class method. Store tokens in an array of strings. each token will be a single char stored as a string or a numerical value stored as a string. To make it easier to parse, the user should enter the infix expression using spaces to separate all parenthesis, operands, and operators.
Set up a function that is passed two floats and a string. In the function use a switch statement based on the char value of the first element of the string to do the appropriate math procedure using the two numbers passed as arguments and returning the result.
Change the infix expression into a postfix expression. This will eliminate any parenthesis. A stack to do this is quite common. Here are some general guidelines to do this:
1)use a loop to evaluate each token in the array of strings infix expression. Evaluate using isdigit() on the first char of the token.
2)If it is a digit the send the token to a different array of strings to be stored in postfix order.
3)If it is a ) the pop the stack until a ( is found, removing ( from stack. Don't send either ) or ( to postfix array of strings.
4)If token is an operator pop stack until there is :
a)a symbol of lower precedence or
b)a right associative symbol of equal precedence
c)then push current token on stack
5)when array of strings in infix order is completely read then pop remaining tokens off stack.
Now use a stack of type float to calculate the result of the postfix expression using the array of strings in postfix order. Here are some general guidelines to do that:
1)Evaluate each token in array of strings in postfix expression using isdigit() on first char of each string.
2)If it is a digit then pass the token to atof() and push the result on the calculation stack.
3)If it is not a digit then pop the reequired # of operands from the stack and call the function you wrote passing the string containing the operator and push the result back on the stack.
4) when the array of strings in postfix notation is all read then value remaining in the stack is the result.
Yea, bravo, you're done.