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

我想打印参与人4。

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


当前回答

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

其他回答

你可以使用下面的方法

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

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

#include <QtCore/QString>

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

这里的一种方法是直接打印输出,如果你的问题需要它。

cout << text << i;

否则,最安全的方法之一就是使用

sprintf(count, "%d", i);

然后复制它到你的“文本”字符串。

for(k = 0; *(count + k); k++)
{ 
  text += count[k]; 
} 

这样,您就有了所需的输出字符串

有关sprintf的更多信息,请参见: http://www.cplusplus.com/reference/cstdio/sprintf

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