int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
字符串流
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
其他回答
cout << text << i;
ostream的<<操作符返回ostream的引用,因此可以继续链接<<操作。也就是说,以上基本等同于:
cout << text;
cout << i;
为了记录,你也可以使用Qt的QString类:
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
另一种可能是Boost。格式:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
cout << text << " " << i << endl;
cout << text << i;