开发者

Concatenating two QStrings with an integer

开发者 https://www.devze.com 2023-03-27 05:50 出处:网络
I want to do something like this in C++ using Qt: int i = 5; QString direc开发者_StackOverflowtory = \":/karim/pic\" + i + \".jpg\";

I want to do something like this in C++ using Qt:

int i = 5;
QString direc开发者_StackOverflowtory = ":/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();
0

精彩评论

暂无评论...
验证码 换一张
取 消