2

How to work with a string to evaluate numbers coming into a condition?

string = "(t>=2 && t<5) || (t<1)";

int c = 0;
for(int t = 0; t < 10; t++){
    if(  {string} )
        c++;
}
jdl
  • 6,151
  • 19
  • 83
  • 132
  • 3
    C++ is not an interpreted language, you know that correct? – David Rodríguez - dribeas Aug 07 '13 at 20:31
  • You can send that string to gpu in an opencl kernel code(C99) but I dont know for host code. Connot do as automated C++(you need to look inside of string, you need a compiler code that compiles). – huseyin tugrul buyukisik Aug 07 '13 at 20:32
  • 1
    Essentially, you can't do this unless you write a function to take in a string and parameters and parse the string using the parameters, returning the 'truth value' of that string. – qaphla Aug 07 '13 at 20:32
  • 1
    Try Lisp. You might have better luck. – Jiminion Aug 07 '13 at 20:33
  • @qaphla, that is what I am trying to avoid... as this is just a simple case. – jdl Aug 07 '13 at 20:34
  • @jdl you cannot avoid it. – Borgleader Aug 07 '13 at 20:35
  • You'll probably have to create a function that parses your string, evaluates it, and returns a bool. You might want to look up implementations of PEMDAS-Compliant calculators in C++, the concept would be the same, but using binary operators instead of arithmetic ones (and a true/false condition instead of total, of course). – IllusiveBrian Aug 07 '13 at 20:35
  • 2
    possible duplicate of [How to parse text for a DSL at compile time?](http://stackoverflow.com/questions/17783393/how-to-parse-text-for-a-dsl-at-compile-time) – Rapptz Aug 07 '13 at 20:42
  • do you know your string at compile time? remove the quotes, convert to lambda function with capture by reference? – im so confused Aug 07 '13 at 20:43

3 Answers3

6

If it's about Qt I would write something like

QScriptEngine e;
e.globalObject().setProperty("t", 123);

bool result = e.evaluate("(t>=2 && t<5) || (t<1)").toBool();
evilruff
  • 3,947
  • 1
  • 15
  • 27
  • trying to use this... I get errors: I #include . But even with just the line "QScriptEngine e;" I get "undefined reference to 'QScriptEngine::QScriptEngine()'... ?? – jdl Aug 08 '13 at 13:57
  • needed: QT += script ... http://stackoverflow.com/questions/18128157/undefined-reference-to-qscriptengineqscriptengine – jdl Aug 08 '13 at 14:13
4

if you want an embedded scripting language (you havent given us the broader context of what you are trying to do) then there are several you can try. Lua is very c friendly (I have used it and it was fine) google's V8 javascript engine is supposed to be very good in c++ (I have not tried it). You can embed python too but many people don't like its syntax

pm100
  • 48,078
  • 23
  • 82
  • 145
-2

You cannot do that in C++ as far as I know.

gr3co
  • 893
  • 1
  • 7
  • 15