문제

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?

도움이 되었습니까?

해결책

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

#include <sstream>
#include <string>

int i = 5;

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

std::string directory = s.str();

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top