Try parse QString to int
Unsolved
General and Desktop
-
Hello,
Looking for function that parses QString to int. In case it can't parse , for example, string contains some non numeric's it should return error.
Something like tryparse() in other languages.
@column
lucky, you're using Qt:
http://doc.qt.io/qt-5/qstring.html#toInt -
Hello,
You can use QString::toInt() method. Which take an optional boolean pointer as argument, giving the result of the conversion.
Just a small example with output
#include <QCoreApplication> #include <QDebug> void test1(); int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); test1(); return 0; } void test1_toInt(const QString &s){ bool ok; int i = s.toInt(&ok, 10); qInfo() << s << " toInt(dec) -> " << i << (ok ? "OK" : "FAILED"); i = s.toInt(&ok, 16); qInfo() << s << " toInt(hex) -> " << i << (ok ? "OK" : "FAILED"); } void test1(){ test1_toInt("123"); test1_toInt("12H"); test1_toInt("H12"); test1_toInt("FF"); test1_toInt("GHI"); }
Output:
"123" toInt(dec) -> 123 OK "123" toInt(hex) -> 291 OK "12H" toInt(dec) -> 0 FAILED "12H" toInt(hex) -> 0 FAILED "H12" toInt(dec) -> 0 FAILED "H12" toInt(hex) -> 0 FAILED "FF" toInt(dec) -> 0 FAILED "FF" toInt(hex) -> 255 OK "GHI" toInt(dec) -> 0 FAILED "GHI" toInt(hex) -> 0 FAILED