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

我想打印参与人4。

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


当前回答

cout << text << " " << i << endl;

其他回答

这些适用于一般字符串(以防你不想输出到文件/控制台,而是存储以供以后使用)。

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;

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

代码示例:

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

你会在控制台看到:

球员4

另一种可能是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,你可以直接把整数写进去,就像

std::cout << text << i;

c++将各种对象转换为字符串的方法是通过字符串流。如果手边没有,就自己创建一个。

#include <sstream>

std::ostringstream oss;
oss << text << i;
std::cout << oss.str();

或者,您可以转换整数并将其附加到字符串。

oss << i;
text += oss.str();

最后,Boost库提供Boost::lexical_cast,它使用类似于内置类型强制转换的语法包装stringstream转换。

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

这也适用于其他方式,即解析字符串。

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