PDA

View Full Version : can Qt help me with this c++ problem?



eric
25th February 2008, 18:58
Hi,

I'd like to do something that I have no idea how to do even in c++ but maybe Qt has someting that can help me?
I was wondering how you would set up an "if statement" where the condition is a variable (and whether that is even possible). This is what I mean:
i have:

if(statement1) dosomething1();
if(statement2) dosomething2();
But I want the statements in the "if clause" to come from a user-made text file. For example if user makes a text file like so:

a<b || a>c
a>=b && a<=C

Then the program is going to execute these lines:


if(a<b || a>c) dosomething1()
if(a>=b && a<=C) dosomething2();

Is this even possible and what would be the best way to do it?
Thans a lot.

Eric

wysota
25th February 2008, 19:15
You need a parser and an evaluator for that. Compiled languages such as C++ are not the best choice here, interpreted languages that have an eval() function available (such as perl or php) are the easiest to use here although also the least safe.

eric
25th February 2008, 19:28
Wysota, thank you for your clarification.
I'd really like to use C/C++ however. What are parser and evaluator? I'd like to attemp this with C/C++.
I apologize for asking a question that is not really a Qt question but maybe just this one time it's OK. Thanks a bunch!

wysota
25th February 2008, 20:00
What are parser and evaluator?
Parser is a function that is able to parse a literal string and form something meaningful for the machine (like a syntax tree). Evaluator is a function that executes the syntax tree.

For instance if you have a "2+3" statement a parser would form a tree with "+" as the root and "2" and "3" as leaves of the tree. Then the evaluator (which can be integrated with the parser) calculates the result of the above to "5".

Google for "bison", "yacc" and take a look here: http://labs.trolltech.com/page/Projects/Compilers/QLALR

pherthyl
25th February 2008, 21:13
As wysota already mentioned, it would be much easier to use a scripting language for this, where you can directly evaluate strings from text files.

You might want to look at QtScript. Then you can build your entire application in C++, but evaluate the user's expressions from a text file in javascript, and use the result in C++ again. Have a look here: http://doc.trolltech.com/4.3/qtscript.html

WinchellChung
26th February 2008, 14:44
I will also note that one can program something like that with the programming language Python (since it has an eval function), and there exist Python bindings for Qt (called PyQt).