Search code examples
c++qtqcustomplot

c++ taking a formula from a string


The goal of this program is to take a formula from user input (I used QLineEdit) and plot the formula (using QCustomPlot for qt). This is the part of the code that I have trouble with:

QVector<double> x(10000), y(10000);
for (int i=0; i<10000; ++i)
{
  double xi = ui->xi_LineEdit->text().toDouble();
  x[i] = xi;
  double yi = ui->yi_LineEdit->text().toDouble();
  y[i] = yi;
}
ui->grafiek->addGraph();
ui->grafiek->graph(0)->setData(x, y);

This code obviously does not work right now. How do I take the formula from user input, by example xi = i/50.0 - 20 and yi = x[i]*x[i], and process it?


Solution

  • The QLineEdit gives you a QString containing a math expression. This type cannot be converted to a double unless it contains nothing but a double. For example, the text "10.34" can be converted from a QString to a double, but the text "10.34 - 18 + 2" cannot, because it must be evaluated first.

    You need to pass the QLineEdit text to a math expression parser. You could write your own if you only need to handle simple arithmetic. This is a worthwhile learning exercise, and you can find numerous examples online, including on SO. If you need more sophisticated parsing, or are in a hurry, then you can google for C++ math parser or similar and use existing code.