I want to convert the Qstring in the QLineEdit to double using QList so that it could perform a calculation and display the results in the QMessagebox. If I can get some suggestions on how this can be done it would be great.
#include <QtGui>
#include <QList>
#include <iostream>
int main (int argc, char* argv[])
{
QApplication app(argc, argv);
QTextStream cout(stdout);
bool ok;
double answer;
do
{
QString mark = QInputDialog::getText(NULL ,"MarkCalc","Enter Mark:", QLineEdit::Normal,"", &ok);
if (ok && !mark.isEmpty())
QList <QString> list;
double am = (mark * 0.20)+(mark * 0.50)+(mark * 0.30);
double ym = am * 0.20;
double em = 75 * 0.40;
double fm = em + ym;
if (em <= 40 && fm >= 50)
cout <<"pass";
else
cout << "fail";
QString response = QString("Your Final Mark: %1 \n\n%5").arg(ym).arg(em);
answer = QMessageBox::question(0, "Final Marks", response,QMessageBox::Yes | QMessageBox::No);
} while (answer == QMessageBox::Yes);
return 0;
}
Here is an example taking the code from the OP and splitting the QString to a QStringList then using foreach to iterate over the list converting each QString in the list to a double then printing the double using cout:
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
int main (int argc, char* argv[]) {
QApplication app(argc, argv);
QTextStream cout(stdout);
bool ok;
double answer;
do{
QString mark = QInputDialog::getText(NULL ,"MarkCalc","Enter Mark:", QLineEdit::Normal,"", &ok);
if (ok && !mark.isEmpty()) {
QStringList list = mark.split(",");
foreach(QString str, list) {
double d = str.toDouble();
cout << d << endl;
}
// double am = (mark * 0.20)+(mark * 0.50)+(mark * 0.30);
// double ym = am * 0.20;
// double em = 75 * 0.40;
// double fm = em + ym;
// if (em <= 40 && fm >= 50)
// cout <<"pass";
// else
// cout << "fail";
// QString response = QString("Your Final Mark: %1 \n\n%5").arg(ym).arg(em);
// answer = QMessageBox::question(0, "Final Marks", response,QMessageBox::Yes | QMessageBox::No);
}
} while (answer == QMessageBox::Yes);
return 0;
}
The following line splits the QString into a QStringList using a comma for the split.
QStringList list = mark.split(",");
After that I use a foreach to iterate over the QStringList one string at a time converting each string to a double and outputting the double one line for each double:
foreach(QString str, list) {
double d = str.toDouble();
cout << d << endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.