我以为这真的很简单,但是却带来了一些困难。如果我有
std::string name = "John";
int age = 21;
如何将它们组合在一起以得到单个字符串"John21"
?
按字母顺序:
std::string name = "John";
int age = 21;
std::string result;
// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);
// 2. with C++11
result = name + std::to_string(age);
// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);
// 4. with FastFormat.Write
fastformat::write(result, name, age);
// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);
// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();
// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);
// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);
// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);
// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
#include <string>
已经包含to_string() )#include <sstream>
(来自标准 C ++)在 C ++ 11 中,您可以使用std::to_string
,例如:
auto result = name + std::to_string( age );
如果您拥有 Boost,则可以使用boost::lexical_cast<std::string>(age)
将整数转换为字符串。
另一种方法是使用字符串流:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
第三种方法是使用 C 库中的sprintf
或snprintf
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
其他海报建议使用itoa
。这不是标准功能,因此如果使用它,则代码将不可移植。有些编译器不支持它。