gpt4 book ai didi

c++ - 如何连接 std::string 和 int

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:38:47 24 4
gpt4 key购买 nike

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

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);
  1. 安全,但速度慢;需要 Boost (仅标题);大多数/所有平台
  2. 是安全的,需要 C++11(to_string() 已经包含在 #include <string> 中)
  3. 安全、快速;需要 FastFormat ,必须编译;大多数/所有平台
  4. (同上)
  5. 安全、快速;需要 the {fmt} library ,可以编译或在仅 header 模式下使用;大多数/所有平台
  6. 安全、缓慢且冗长;需要 #include <sstream> (来自标准 C++)
  7. 脆弱(您必须提供足够大的缓冲区)、快速且冗长; itoa() 是一个非标准扩展,不保证适用于所有平台
  8. 脆弱(您必须提供足够大的缓冲区)、快速且冗长;不需要任何东西(是标准的 C++);所有平台
  9. 很脆弱(你必须提供足够大的缓冲区),probably the fastest-possible conversion , 冗长;需要 STLSoft (仅标题);大多数/所有平台
  10. 安全(您不会在一条语句中使用多个 int_to_string() 调用),快速;需要 STLSoft (仅标题);仅限 Windows
  11. 安全,但速度慢;需要 Poco C++ ;大多数/所有平台

关于c++ - 如何连接 std::string 和 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56175980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com