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

我想打印参与人4。

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


当前回答

你的例子似乎表明你想要显示一个字符串后面跟着一个整数,在这种情况下:

string text = "Player: ";
int i = 4;
cout << text << i << endl;

会很好。

但是,如果你要把字符串存储在某个地方或者传递给别人,并且经常这样做,你可能会从重载加法运算符中获益。我在下面演示一下:

#include <sstream>
#include <iostream>
using namespace std;

std::string operator+(std::string const &a, int b) {
  std::ostringstream oss;
  oss << a << b;
  return oss.str();
}

int main() {
  int i = 4;
  string text = "Player: ";
  cout << (text + i) << endl;
}

事实上,你可以使用模板来让这种方法更强大:

template <class T>
std::string operator+(std::string const &a, const T &b){
  std::ostringstream oss;
  oss << a << b;
  return oss.str();
}

现在,只要对象b有一个已定义的流输出,您就可以将它附加到您的字符串(或者至少是其副本)。

其他回答

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

这里的一种方法是直接打印输出,如果你的问题需要它。

cout << text << i;

否则,最安全的方法之一就是使用

sprintf(count, "%d", i);

然后复制它到你的“文本”字符串。

for(k = 0; *(count + k); k++)
{ 
  text += count[k]; 
} 

这样,您就有了所需的输出字符串

有关sprintf的更多信息,请参见: http://www.cplusplus.com/reference/cstdio/sprintf

如果你用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);

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

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

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;
cout << "Player" << i ;