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

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

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


当前回答

如果你使用MFC,你可以使用CString

CString nameAge = "";
nameAge.Format("%s%d", "John", 21);

托管c++也有一个 字符串格式化程序。

其他回答

#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是非标准的。

作为一行:name += std::to_string(年龄);

如果你使用MFC,你可以使用CString

CString nameAge = "";
nameAge.Format("%s%d", "John", 21);

托管c++也有一个 字符串格式化程序。