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++ ?
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++ ?
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.
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";
}
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.