C++ 用一个整数连接两个 QStrings
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7011447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenating two QStrings with an integer
提问by Karim M. El Tel
I want to do something like this in C++ using Qt:
我想在 C++ 中使用 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?
where+
表示我想连接字符串和整数(即directory
应该是:/karim/pic5.jpg
)。我怎样才能做到这一点?
回答by Sebastian Negraszus
回答by Cubbi
(EDIT: this is an answer to the question before the edit that mentioned QString. For QString, see the newer answer)
(编辑:这是对提到 QString 的编辑之前问题的答案。对于 QString,请参阅较新的答案)
This can be done as a very similar one-liner using C++11:
这可以使用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:
对于较旧的编译器,它可以用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
回答by Jens Luedicke
Have a look at stringstream:
看看字符串流:
http://cplusplus.com/reference/iostream/stringstream/
http://cplusplus.com/reference/iostream/stringstream/
ostringstream oss(ostringstream::out);
oss << ":/karim/pic";
oss << i
oss << ".jpg";
cout << oss.str();
回答by Tobias Schlegel
#include <sstream>
#include <string>
int i = 5;
std::stringstream s;
s << ":/karim/pic" << i << ".jpg";
std::string directory = s.str();