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

我想打印参与人4。

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


当前回答

cout << text << i;

其他回答

另一种可能是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;

ostream的<<操作符返回ostream的引用,因此可以继续链接<<操作。也就是说,以上基本等同于:

cout << text;
cout << i;

使用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);

你的例子似乎表明你想要显示一个字符串后面跟着一个整数,在这种情况下:

string text = "Player: ";
int i = 4;
cout << text << i << endl;

会很好。

但是,如果你要把字符串存储在某个地方或者传递给别人,并且经常这样做,你可能会从重载加法运算符中获益。我在下面演示一下:

#include <sstream>
#include <iostream>
using namespace std;

std::string operator+(std::string const &a, int b) {
  std::ostringstream oss;
  oss << a << b;
  return oss.str();
}

int main() {
  int i = 4;
  string text = "Player: ";
  cout << (text + i) << endl;
}

事实上,你可以使用模板来让这种方法更强大:

template <class T>
std::string operator+(std::string const &a, const T &b){
  std::ostringstream oss;
  oss << a << b;
  return oss.str();
}

现在,只要对象b有一个已定义的流输出,您就可以将它附加到您的字符串(或者至少是其副本)。