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

QStringList index out of range



  • Hey Everyone,

    I'm trying to extract some informations from a QStringList. I keep getting an error that the index is out of range.

    Here's how the List is constructed.

    QString selectedTarget = ui->TargetList->currentItem()->text();
    QStringList List = selectedTarget.split(QRegExp("\\s+"));
    

    The String selected Target contains the Hostname and the Ip Adress of a target device I'm trying to connect to. I Split this String in two separate String (Hostname and Address). I then try to store each of them in a different string but I get an error. So I tried to display the content and size of the List with the following code:

    qDebug() << List.count();
    	for (int f = 0;  f <= List.size() ; f++)
    	{
    		qDebug() << List.takeAt(f);
    	}
    

    List size is 2 which is right. But only the first Item of the list gets displayed. Within the second iteration i get the error that index out of range. which makes no sense the size of my list is 2 and i only iterated once.

    why is this happening?



  • takeAt removes the item of index f.
    If you just want to print it, use at instead.
    Do note that all the take* functions in Qt will remove something from the container / parent.


  • Moderators

    @JohnSRV additionally to what @Bonnie said, your end condition is f <= List.size()that should be < otherwise it will make 3 try's to instead of the allowed 2


Log in to reply