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

我想打印参与人4。

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


当前回答

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

其他回答

这里有一个小的转换/附加示例,其中有一些我以前需要的代码。

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}

输出将是:

/dev/video
/dev/video456
/dev/video321
/dev/video123

请注意,在最后两行中,您在实际打印出修改后的字符串之前保存了它,如果需要,您可以稍后使用它。

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

代码示例:

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

你会在控制台看到:

球员4

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