int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
我能想到的最简单的方法是: 它将作为单个字符串和字符串数组工作。 我正在考虑一个字符串数组,因为它是复杂的(有点相同将跟随字符串)。 我创建了一个名称数组,并附加了一些整数和字符与它,以显示它是多么容易附加一些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;
}
}
其他回答
为了记录,如果您想在实际输出字符串之前创建字符串,还可以使用std::stringstream。
使用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 << endl;
你可以使用下面的方法
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
字符串流
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;