int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
这里的一种方法是直接打印输出,如果你的问题需要它。
cout << text << i;
否则,最安全的方法之一就是使用
sprintf(count, "%d", i);
然后复制它到你的“文本”字符串。
for(k = 0; *(count + k); k++)
{
text += count[k];
}
这样,您就有了所需的输出字符串
有关sprintf的更多信息,请参见: http://www.cplusplus.com/reference/cstdio/sprintf
其他回答
为了记录,如果您想在实际输出字符串之前创建字符串,还可以使用std::stringstream。
这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。
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;
为了记录,你也可以使用Qt的QString类:
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
printf("Player %d", i);
(你可以给我的答案投票;我仍然讨厌c++的I/O操作符。)
:-P
我能想到的最简单的方法是: 它将作为单个字符串和字符串数组工作。 我正在考虑一个字符串数组,因为它是复杂的(有点相同将跟随字符串)。 我创建了一个名称数组,并附加了一些整数和字符与它,以显示它是多么容易附加一些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;
}
}