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

我想打印参与人4。

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


当前回答

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

其他回答

printf("Player %d", i);

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

:-P

cout << text << i;

你可以使用下面的方法

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

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

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