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

我想打印参与人4。

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


当前回答

如果使用Windows/MFC,并且需要字符串的即时输出,请尝试:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);

其他回答

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

#include <QtCore/QString>

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

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

:-P

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

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

如果使用Windows/MFC,并且需要字符串的即时输出,请尝试:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);