我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
我原以为这很简单,但它出现了一些困难。如果我有
std::string name = "John";
int age = 21;
我如何结合他们得到一个单一的字符串“John21”?
当前回答
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
其他回答
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
在c++ 11中,你可以使用std::to_string,例如:
auto result = name + std::to_string( age );
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}
无耻地从http://www.research.att.com/~bs/bs_faq2.html窃取。
在我看来,最简单的答案是使用sprintf函数:
sprintf(outString,"%s%d",name,age);
你可以像这样使用C函数itoa():
char buf[3];
itoa(age, buf, 10);
name += buf;