Hello!
I try to use a parser for simple math expressions from a QString, as 3+2.(5^2)/9....and so on (no variables to calculate, just numbers). I started with a recursive-descent parser, but then I found a simpler solution with QJSEngine:
#include "math.h"
#include "expression_calc.h"
#include "ui_expression_calc.h"
#include "QDebug"
#include <QApplication>
#include <QJSEngine>
#include <QJSValue>
#include <QObject>
Expression_calc
::Expression_calc(QWidget *parent
) : ui(new Ui::Expression_calc)
{
ui->setupUi(this);
}
Expression_calc::~Expression_calc()
{
delete ui;
}
void Expression_calc::on_CalcButton_clicked()
{
QString expression
= ui
->exp
->text
();
QJSEngine parsexpression;
double result=parsexpression.evaluate(expression).toNumber();
ui
->Result
->setText
(QString::number(result
));
}
#include "math.h"
#include "expression_calc.h"
#include "ui_expression_calc.h"
#include "QDebug"
#include <QApplication>
#include <QJSEngine>
#include <QJSValue>
#include <QObject>
Expression_calc::Expression_calc(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Expression_calc)
{
ui->setupUi(this);
}
Expression_calc::~Expression_calc()
{
delete ui;
}
void Expression_calc::on_CalcButton_clicked()
{
QString expression= ui->exp->text();
QJSEngine parsexpression;
double result=parsexpression.evaluate(expression).toNumber();
ui->Result->setText(QString::number(result));
}
To copy to clipboard, switch view to plain text mode
Ok, very simply, ...but this method can interpret just +,-,*,/,()...
I decide to manipulate the main QString expression with a
expression.replace("sqrt","Math.sqrt");
expression.replace("abs","Math.abs");
expression.replace("cos","Math.cos");
......
expression.replace("sqrt","Math.sqrt");
expression.replace("abs","Math.abs");
expression.replace("cos","Math.cos");
......
To copy to clipboard, switch view to plain text mode
Not very elegant, but a fast solution. In add, as I have to store the expressions, I can save the corrected versions.
All it works, except for the damned "^". Math requires "pow(3,2)" instead of common expression 3^2, does someone have a fast solution to workaround this, or you suggest to return to a recursive-descent parser?
Thanks!
Bookmarks