Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert an expression to its value

Status
Not open for further replies.

Triac

Technical User
Jan 29, 2002
20
IT
I got a problem, but I don't know if it is possible to resolve it...
I have a string, let's say

CString str = "4*2.5";

and I'd like to do a thing like this

double result = unknownFunction(str);

obtaining result = 10;

Is it possible to do it?
(Obviously, if so, how? :eek:) )
Don't matter if there's not just a function, any hint will be appreciated.
Thanks to you all
 
If you can assume that there is only one operation, it is not so hard. Something like:
double First, Second;
CString buff;
if (int pos = str.Find('*'))
{
buff = str.Left(pos);
First = atof(buff);
buff = str.Right(str.Len()-(pos+1));
Second = atof(buff);
return First * Second;
}

if (int pos = str.Find('/'))
{
buff = str.Left(pos);
First = atof(buff);
buff = str.Right(str.Len()-(pos+1));
Second = atof(buff);
return First / Second;
}

keep going like that for + and -

If there are multiple operations, you would do something the same, but you would have to consider order of operation.
 
Thanks, you even wrote me the code! Actually I was looking for something more general, bur now I guess your method is the only one I can use.Maybe I have to 'defrag my mind' and simplify everything.
Thank MinnisotaFreezing
 
In college I needed to write a compiler that handled math operations. The steps taken were to first look at the orders of operation. We parsed the string a character at a time keeping in mind what took precidence. we then pushed these things into one of two stacks. One stack was for operations and the other was for numbers. When finished we popped the stacks and numbers.
i.e.
NumberStack.pop OperationStack.pop NumberStack.pop

This made it very easy to calculate what to do as the stack was set up properly. All operations were enumerated and switched on to get the end result.


I hope this broad explanation gives you some ideas on a possible implementation of how to accomplish the task.

Matt
 
I like it! I guess that's the right way. s-)

Thanks to you both!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top