How can i calculate Qstring data ?
-
[quote author="webadana" date="1299997503"]i have a Qstring data like "43+40/2"
i want to calculate it each other.. when i debug it seem "43+40/2" but i want to return it 53..[/quote]Seems to me you need to start working on simpler problems first. QString isn't a calculator. You need to parse the string and translate it to math operations. Get the order of execution right. Lots of stuff to think about.
Also, 43 + 40 / 2 = 63, but you probably made a typo there.
-
I would approach this using the QtScript module. Put your expression to be evaluated into a QString, add some wrapper code to create a QScriptValue from it (ie add in the function signature and curly braces). Then evaluate the resulting QScriptObject using a QScriptEngine instance.
Something along these lines...
@
QScriptEngine engine;
QString function( myFunction() { return 43 + 40 / 2; } );// Tell engine about the function
engine.evaluate( function );// Get a "function pointer" type object
QScriptValue scriptFunction = engine.globalObject().property( "myFunction" );// Call the function
double result = scriptFunction.call().toNumber();
@Note that with this approach you can also pass arguments into the function too. See the QtScript docs for more details.
-
thank you for your answers..
@
QString x = "30.5+40/2";
QScriptEngine myEngine;
QScriptValue x2 = myEngine.evaluate(x);
qDebug() << x2.toNumber();
@
i use this code and its work but i cant calculate sin, cos.. how can i calculate sin cos..
i try to @ZapB 's code but it didn't calculate too.. (or i couldn't :))
thank you very much..:) -
A hack that comes to mind is some regular expression magic. Why not simply insert the "Math." at the appropriate place in your string?
Alternatively, you can define the functions you want to have available in your scripting environment yourself, so you don't need to modify the input string.
-