[SOLVED] detecting variables if exist



  • i dont know if this is possible with Qt.

    if PHP detect variables if exist using isset(), how Qt detects it?

    I want to use it in a QString split().

    @
    QString str = "hello - world";
    QStringList s_str = str.split("-");
    if (isset(s_str[0])) { // like this one
    // exist
    }
    if (isset(s_str[3])) { // like this one also
    // not exist
    }
    @



  • That's totally nonsense, C++ is a static language and all identifiers must be declared prior their use. Simply change the logic and ask if the index you're looking for is between 0 and s_str.size()-1.



  • This is an array/list, not a variable. You can check how many elements are in the list by using the size() function. For the first one, where you check if [0] exists, you can use isEmpty().

    C++ Doesn't let you access a variable that may not have been created.



  • In fact, in this particular case you are not even checking for a variable. You are using the overloaded operator[] of the QStringList class.

    I don't know how QStringList handles a index out of the boundaries but it could be anything from returning a empty QString to a segmentation fault.



  • In fact, QStringList is a QList which makes an assert (Q_ASSERT_X) and then accesses the date.

    In case of out of bounds access, Q_ASSERT_X will lead to qt_assert_x which will lead qFatal. This leads to qt_message(QtFatalMsg, ...); and this to

    • MSVS debug version: _CrtDbgReport & _CrtDbgBreak
    • MINGW or UNIX: abort();
    • else: exit(1);

    So your application will exit.



  • What you can do is check if the string is empty, of course. It will be as soon as you declare it. It is not the same as in PHP, because there if you set it to an empty string, it is still set. But perhaps it is all you need. Check out QString::isEmpty().



  • But that only gives you, whether the source string is empty.
    if you want to check, how many elements are in the list, you have to do it the following way:

    @
    QString str = "hello - world";
    QStringList s_str = str.split("-");
    if (s_str.count() > 0)) { // like this one
    // exist
    }
    if (s_str.count() > 3) { // like this one also
    // not exist
    }
    @


Log in to reply
 

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