int i = 4;
string text = "Player ";
cout << (text + i);

我想打印参与人4。

上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?


当前回答

如果你用cout,你可以直接把整数写进去,就像

std::cout << text << i;

c++将各种对象转换为字符串的方法是通过字符串流。如果手边没有,就自己创建一个。

#include <sstream>

std::ostringstream oss;
oss << text << i;
std::cout << oss.str();

或者,您可以转换整数并将其附加到字符串。

oss << i;
text += oss.str();

最后,Boost库提供Boost::lexical_cast,它使用类似于内置类型强制转换的语法包装stringstream转换。

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

这也适用于其他方式,即解析字符串。

其他回答

cout << "Player" << i ;

这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。

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;

为了记录,如果您想在实际输出字符串之前创建字符串,还可以使用std::stringstream。

printf("Player %d", i);

(你可以给我的答案投票;我仍然讨厌c++的I/O操作符。)

:-P

为了记录,你也可以使用Qt的QString类:

#include <QtCore/QString>

int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData();  // prints "Player 4"