int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
printf("Player %d", i);
(你可以给我的答案投票;我仍然讨厌c++的I/O操作符。)
:-P
其他回答
printf("Player %d", i);
(你可以给我的答案投票;我仍然讨厌c++的I/O操作符。)
:-P
这里有一个小的转换/附加示例,其中有一些我以前需要的代码。
#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
请注意,在最后两行中,您在实际打印出修改后的字符串之前保存了它,如果需要,您可以稍后使用它。
另一种可能是Boost。格式:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
cout << text << " " << i << endl;
我能想到的最简单的方法是: 它将作为单个字符串和字符串数组工作。 我正在考虑一个字符串数组,因为它是复杂的(有点相同将跟随字符串)。 我创建了一个名称数组,并附加了一些整数和字符与它,以显示它是多么容易附加一些int和字符字符串,希望它有帮助。 长度只是用来衡量数组的大小。如果您熟悉编程,那么size_t是一个无符号整型
#include<iostream>
#include<string>
using namespace std;
int main() {
string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
int length = sizeof(names) / sizeof(names[0]); //give you size of array
int id;
string append[7]; //as length is 7 just for sake of storing and printing output
for (size_t i = 0; i < length; i++) {
id = rand() % 20000 + 2;
append[i] = names[i] + to_string(id);
}
for (size_t i = 0; i < length; i++) {
cout << append[i] << endl;
}
}