Using variables ending with numbers
-
According to the docs of Qt5 it would more like:
@
QString str;
str = "nom%1";str.arg("", "X");
@[edit, running into an issue with the editor here.
the first argument of str.arg shall be "% 1 f" without spaces. ]However, I am not sure it looks stupid and might be wrong in the docs. I do not use QString very often, more the std::string variant.
But this should work:
@
QString str;
str = "nom";
QString str2 = str + QString ("X");
@
or
@
QString str;
str = "nom";
QString str2 = str + "X";
@ -
Hi,
Thank you for your reply.
My request was not clear. Let me put it that way:@
in header
QString nom1;
QString nom2;
@
@
in .cpp
nom1="Sam"
nom2"Pierre";QString st="nom";
QString st2=st+"1";
st2="Paul";
// nom1 should now be : Paul - but it isn't , only st2="Paul"
@ -
@QStringList nom;
nom.append("Sam");
nom.append("Pierre");QString someOtherString = nom.at(0); // will be "Sam"@
This isn't a scripting language, so building variable identifiers from strings is rightly discouraged, for performance, security and anti-spaghetti-code reasons. Through hackery (a.k.a. meta object system), it is possible though. But don't do it. Leads to bad programs, and we've got plenty of those.
-
As already explained by DerManu.
Or you may use "QMap":http://qt-project.org/doc/qt-5.0/qtcore/qmap.html .
@
QMap<QString, QString> myMap;
myMap["nom1"]="Sam";
myMap["nom2"]="Pierre";
myMap["nom3"]="Paul";QString st = "nom";
QString st2 = st + "1";qDebug() << myMap[st2];
@
should work. -
@koahnig, I slightly disagree with the QMap usage here. Because that number in the end of "nom" just screams for an integer index based container like QVector or QList (@phil: QStringList is just QList<QString>), and so one should use them, and not the more key-generic QMap<QString, QString>. If non-continuous index ranges are needed, QMap<int, QString> would be okay.
-
[quote author="DerManu" date="1371374572"]@koahnig, I slightly disagree with the QMap usage here. Because that number in the end of "nom" just screams for an integer index based container like QVector or QList (@phil: QStringList is just QList<QString>), and so one should use them, and not the more key-generic QMap<QString, QString>. If non-continuous index ranges are needed, QMap<int, QString> would be okay.[/quote]
Yes, you are right, but the question is what is the real case at the end. If it is a simplified example and the names will be a bit more complex and not just a number appended, it might make sense. -
This post is deleted!