Calculating value stored in a string C++

Associate
Joined
22 Nov 2005
Posts
319
Location
Alnwick, Northumberland
Im using visual c++ and I have a class which is used for calculating mathematical expressions, but im having difficulties calculating the value, because the expression is stored as a string. I need the expression in a string, because it is used in some of my other classes.
How do i calculate the value of the string?
eg
CString ExpressionStr = "2.3*sin(23)/1.7";
double Value = // value of ExpressionStr

Any help is appreciated
 
Last edited:
Wang Computer said:
Wouldn't it be easier to store the data as values, and cast them to a string when and where needed? That's what I would do...

He's not storing the data as a string, he's storing the formula to put the data in as a string.

Una is correct - You'll have to write your own parser, which isn't that easy, but a worthwhile experience :)
 
growse said:
He's not storing the data as a string, he's storing the formula to put the data in as a string.

To be fair, he didn't explicitly state that. I got the impression from his example that both the syntax of the formula and its variables are part of the same piece of data; i.e. the string. There is no need the parse the formula AND the variables/constants in two steps.

My advice is to avoid using strings in C++ at all costs. They are messy, inefficient to parse and there are ways around them. For instance, when storing an expression, why not have some sort of linked list that would contain the various operands and operators in a logical order? This LL can be accessed from anywhere in your code structure if you deem necessary. You can then write logic which will interpret the data from the nodes and perform the calculations - some case switches and rules on the operator priority would work.

There are probably other, more effective solutions...

Just my 2 pennies.
 
Back
Top Bottom