19

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?

4
  • 11
    C++ concatenate string and int stackoverflow.com/questions/191757/c-concatenate-string-and-int There is an answer with 8 ways to do it in there.
    – dee-see
    Aug 10, 2011 at 13:22
  • The tags indicate he wants an answer for qt, the answers in the "duplicate" don't provide that.
    – JoeG
    Aug 10, 2011 at 13:47
  • 6
    Ok, I missed it being a Qt question, voted for reopen. The solution is: QString dir = ":/karim/pic" + QString::number(i) + ".jpg"; Aug 10, 2011 at 13:53
  • This is not the optimal solution, but since all the solutions tell how to do it with std::string, if you ever need a QString and you have an std::string, use this function Aug 10, 2011 at 14:09

4 Answers 4

39

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

QString directory = QString(":/karim/pic%1.jpg").arg(i);
1
12

(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

2
  • Interesting. I never knew, all this time that there was an overload for operator+(const char *, const std::string &), and so I would always have to wrap my literals in a string constructor. Aug 10, 2011 at 13:51
  • @Karim M. El Tel: Ohh, since it's a QString (after edit), go with hexa's comment. Hopefully it will get reopened so it can be posted as an answer.
    – Cubbi
    Aug 10, 2011 at 14:05
2
#include <sstream>
#include <string>

int i = 5;

std::stringstream s;
s << ":/karim/pic" << i << ".jpg";

std::string directory = s.str();
1
  • 1
    I think it's s.str(), not s.string() Aug 10, 2011 at 13:26
2

Have a look at stringstream:

http://cplusplus.com/reference/iostream/stringstream/

ostringstream oss(ostringstream::out);

oss << ":/karim/pic";
oss << i
oss << ".jpg";

cout << oss.str();
1
  • You need to include <sstream>. Aug 10, 2011 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.