0

I get a string in C++ after evaluation like " true && (false || true) "

Need to evaluate this string . In PHP, we use eval function to achieve this. How do we achieve this in C++ ?

caspersky 48
  • 239
  • 1
  • 4
  • 11
  • 1
    It is unclear what you are asking. Can you post the code you tried to use and the specific error you encountered? – utnapistim Sep 16 '13 at 08:10
  • possible duplicate of [Boolean expression (grammar) parser in c++](http://stackoverflow.com/questions/8706356/boolean-expression-grammar-parser-in-c) – nikolas Sep 16 '13 at 08:17

3 Answers3

5

In C++ there is no eval function built in. If you need this functionality, you have to find and use an external library or implement it yourself.

I don't know which is the best external library that would do the job. You could use the JavaScript interpreter V8 or the Ruby interpreter, but they are too heavy-weight.

I would implement it like this. I'd split the input string to tokens, i.e. vector<string>: {"true", "&&", "(", "false", "||", "true", ")"}. Then I would iterate over this input list, and push the elements to a stack. Before each push I'd look at the top few elements on the stack, and do the evaluation, like this:

(empty stack, push)
"true"
"true", "&&",
"true", "&&", "(",
"true", "&&", "(", "false"
"true", "&&", "(", "false", "||",
"true", "&&", "(", "false", "||", "true"  (evaluate ||)
"true", "&&", "(", "true"
"true", "&&", "(", "true", ")"  (evaluate parens)
"true", "&&", "true"  (evaluate &&)
"true"

This technique is a simplified version of the LR(1) parsing of context-free grammars.

You can implement the parser yourself or use flex and bison (or some other tools, see other answers) to generate it for you.

pts
  • 80,836
  • 20
  • 110
  • 183
2

Simply compare the string with whatever words you want to use for the boolean value.

For example:

bool parseBoolean(const std::string &str) {
    return str == "true" || str == "yes" || str == "on";
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

There are no built-in facilities into C/C++ for code evaluation (due to the compiled nature of the languages I suppose) therefore you need to create a parser manually.

I imagine that the complexity of your example dwells in the definition of a grammar for balanced logic expressions (and, or, and maybe not). You could use Spirit using the boost libraries which lets you define a grammar in a declarative fashion.

There is already an answered question here on SO: Parsing Boolean Expression in C++, take a look at the correct answer by sehe which uses spirit and provides you a working piece of code.

Community
  • 1
  • 1
rano
  • 5,616
  • 4
  • 40
  • 66