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

我想打印参与人4。

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


当前回答

使用c++ 11,你可以写:

#include <string>     // to use std::string, std::to_string() and "+" operator acting on strings 

int i = 4;
std::string text = "Player ";
text += std::to_string(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;

另一种可能是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;
}
printf("Player %d", i);

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

:-P

cout << text << " " << i << endl;
cout << "Player" << i ;