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

我想打印参与人4。

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


当前回答

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

其他回答

你也可以尝试用std::string::push_back连接玩家的号码:

代码示例:

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

你会在控制台看到:

球员4

cout << "Player" << i ;
cout << text << 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);

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

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