Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating two QStrings with an integer

Tags:

c++

qt

qstring

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?

like image 518
Karim M. El Tel Avatar asked Aug 10 '11 13:08

Karim M. El Tel


People also ask

How do I concatenate Qstrings?

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.

Can you concatenate a string and an integer?

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.

How do I combine two string values?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator.


2 Answers

Qt's idiom for things like this is the arg()function of QString.

QString directory = QString(":/karim/pic%1.jpg").arg(i);
like image 67
Sebastian Negraszus Avatar answered Sep 27 '22 21:09

Sebastian Negraszus


(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

like image 28
Cubbi Avatar answered Sep 27 '22 21:09

Cubbi