Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Try parse QString to int



  • 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.


  • Moderators



  • 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
    

Log in to reply