Convert QStringList to multiple integers



  • I have a QStringList like ["2", "3", "4"] and I'm trying to compare numbers in this QStringList to a QString which only has one number in it.

    QStringList list = ["2", "3", "4"];
    QString number = "3";
    
    for (int i=0 ; i<3 ; i++)
    {
               if (number == list.at(i))
               {
                     //do something
               }
              else
              {
                //do something else 
              }
    }
    

    I am not able to make it work. What am I doing wrong?

    Any suggestions will be greatly appreciated.
    Thank you


  • Lifetime Qt Champion

    Hi,

    What exactly is not working ?

    On a side note, why not use a QVector<int> rather than a QStringList of numbers ?

    You should also rather write your for loop based on your container rather than use fixed values:

    for (const QString& value : list) {
        if (value == "3") {
            // Do something 
        } else {
            // Do other something 
        }
    }
    


  • @SGaist said in Convert QStringList to multiple integers:

    What exactly is not working ?

    It acts like if true condition was not met.

    Even with your code its doing the same thing.


  • Lifetime Qt Champion

    This works fine:

    #include <QtDebug>
    #include <QStringList>
    
    int main(int argc, char *argv[])
    {
        Q_UNUSED(argc);
        Q_UNUSED(argv);
    
        QStringList list{"1", "2", "3"};
        for (const QString& value : list) {
            if (value == QStringLiteral("3")) {
                // Do something
                qDebug() << "Found";
            } else {
                // Do other something
                qDebug() << "Nop" << value;
            }
        }
        return 0;
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.