I want to do something like this in C++ using Qt:
int i = 5;
QString directory = ":/karim/pic" + i + ".jpg";
where +
means I want to concatenate the strings and the integer (that is, directory
should be :/karim/pic5.jpg
). How can I do this?
Imagine we gave a sequence (for example aQVector) of strings that we want to concatenate instead of having them in separate variables. With std::accumulate, string concatenation would look like this: QVector<QString> strings{ . . . }; std::accumulate(strings. cbegin(), strings.
To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator.
Qt's idiom for things like this is the arg()
function of QString.
QString directory = QString(":/karim/pic%1.jpg").arg(i);
(EDIT: this is an answer to the question before the edit that mentioned QString. For QString, see the newer answer)
This can be done as a very similar one-liner using C++11:
int i = 5;
std::string directory = ":/karim/pic" + std::to_string(i) + ".jpg";
Test: https://ideone.com/jIAxE
With older compilers, it can be substituted with Boost:
int i = 5;
std::string directory = ":/karim/pic" + boost::lexical_cast<std::string>(i) + ".jpg";
Test: https://ideone.com/LFtt7
But the classic way to do it is with a string stream object.
int i = 5;
std::ostringstream oss;
oss << ":/karim/pic" << i << ".jpg";
std::string directory = oss.str();
Test: https://ideone.com/6QVPv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With