我原以为这很简单,但它出现了一些困难。如果我有

std::string name = "John";
int age = 21;

我如何结合他们得到一个单一的字符串“John21”?


当前回答

#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 );

常见答案:itoa()

这很糟糕。正如这里指出的,Itoa是非标准的。

#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窃取。

#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();

如果你有c++ 11,你可以使用std::to_string。

例子:

std::string name = "John";
int age = 21;

name += std::to_string(age);

std::cout << name;

输出:

John21