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

我想打印参与人4。

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


当前回答

你可以使用下面的方法

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

其他回答

printf("Player %d", i);

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

:-P

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

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

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

cout << "Player" << i ;