int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
int i = 4;
string text = "Player ";
cout << (text + i);
我想打印参与人4。
上面显然是错误的,但它显示了我在这里要做的事情。是否有一个简单的方法来做到这一点,或者我必须开始添加新的包含?
当前回答
这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。
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;
其他回答
如果使用Windows/MFC,并且需要字符串的即时输出,请尝试:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);
cout << "Player" << i ;
为了记录,如果您想在实际输出字符串之前创建字符串,还可以使用std::stringstream。
另一种可能是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;
否则,最安全的方法之一就是使用
sprintf(count, "%d", i);
然后复制它到你的“文本”字符串。
for(k = 0; *(count + k); k++)
{
text += count[k];
}
这样,您就有了所需的输出字符串
有关sprintf的更多信息,请参见: http://www.cplusplus.com/reference/cstdio/sprintf