Convert a Logical Expression (string) to a Boolean value

Hi,

I'm trying to figure out how to convert an expression like this:
string s = "( 1 & ( 0 | 1))";
to a Boolean value.

In the case above:
bool b = ( 1 && ( 0 || 1));
Which means - true;

I prefer to use '|' and '&' instead of '||' and '&&' in the string.

Any ideas?
Last edited on
You need an expression parsing library like muParser. This is no trivial task - every wondered why it takes so long to compile your programs?
There is no a way to do it?

My program searches the logical expression in a document.
For example, if you search: "(ab & cd)"
It searches if the words "ab" and "cd" are in the document.

Since the expressions can get pretty complicated (by brackets etc.), and since I can get the Boolean value of each part in the expression, I thought to read the expression char by char (after removing spaces), and to "compose" a string:
If I encounter '(' or ')' - I just add it to the string, and if I get a word to search, like "ab", I use a function to find out if it exists in the document (1/true) or not (0/false).
So if "ab" exists and "cd" not, my new string will be: "(1&0)"
If this was a Boolean expression, the compiler would bring me it's value simply.

My program has to know the expression's logical value.

Can you help?
Last edited on
LB wrote:
You need an expression parsing library like muParser.
AmitH wrote:
There is no a way to do it?

How can "use C++ code that someone else has already written" evaluate to "not possible"?


Expression is not a flat string. Expression is usually a tree. The tree is first constructed from the string. Then the tree is evaluated (perhaps multiple times).

Why a tree? Look at "3*(4+7)".
The 4 and 7 have to be evaluated before the +.
The 3 and + have to be evaluated before the *.

The * is the root of the tree. It has two child nodes: 3 and +. The +has two child nodes: 4 and 7.

You booleans are lazy: evaluation of the first child node may be sufficient. That, however, is just a different order of traversing the tree.
Topic archived. No new replies allowed.