[SOLVED] detecting variables if exist
-
wrote on 7 Jan 2011, 02:22 last edited by
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
}
@ -
wrote on 7 Jan 2011, 02:27 last edited by
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.
-
wrote on 7 Jan 2011, 02:30 last edited by
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.
-
wrote on 7 Jan 2011, 02:36 last edited by
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.
-
wrote on 7 Jan 2011, 08:47 last edited by
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.
-
wrote on 7 Jan 2011, 09:45 last edited by
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().
-
wrote on 7 Jan 2011, 10:32 last edited by
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
}
@
1/7