int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
你可以使用下面的方法
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
其他回答
这里的一种方法是直接打印输出,如果你的问题需要它。
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;
ostream的<<操作符返回ostream的引用,因此可以继续链接<<操作。也就是说,以上基本等同于:
cout << text;
cout << i;
你也可以尝试用std::string::push_back连接玩家的号码:
代码示例:
int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;
你会在控制台看到:
球员4
你可以使用下面的方法
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
cout << text << i;