【问题标题】:How to compose a string and an int to a string? [duplicate]如何将一个字符串和一个 int 组合成一个字符串? [复制]
【发布时间】:2016-12-19 12:42:12
【问题描述】:

在工作中,我们不得不将 iostream 替换为 void output(std::string) 函数:

std::cout << "This is some output." << '\n';

<--Old--
--New-->

output("This is some output");

当然,我有很多代码将字符串和 int 组合在一起,并且我已经找到了解决此问题的一种可能方法:

int some_value = 5
std::cout << "Some value: " << some_value << '\n';

<--Old--
--New-->

int some_value = 5;
std::stringstream tmp_stream;
tmp_stream << "Some value: " << some_value << '\n';
output(tmp_stream.str());

但我不太喜欢这个解决方案,因为它引入了两行额外的代码和一个额外的一次性使用变量。你知道其他更优雅的解决方案吗?

【问题讨论】:

  • 麻烦。我正在建议 OP 编写一个output_stream 类,它将输出发送到函数output。要么通过streambuf 正确完成,要么只编写一个包含operator &lt;&lt; 的类。这样他们只需将std::cout 更改为g_output。无法写出该答案,因为该问题已作为重复问题关闭。
  • 感谢您的回复!
  • @johannesmik 比链接副本更通用的版本或此处的答案是创建可变参数函数模板,例如参见ideone.com/eVjnbv(注释块适用于 c++17)。这样您只需将std::cout &lt;&lt; a &lt;&lt; b &lt;&lt; c; 转换为to_output(a, b, c);

标签: c++ string c++11 iostream


【解决方案1】:

您可以使用std::to_string 将数字类型转换为std::string,然后在调用output 之前将它们连接起来

output("Some value: " + std::to_string(some_value));

【讨论】:

    【解决方案2】:

    你可以简单地使用 std::to_string(value) 函数并结合两个 std::string

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 2020-10-30
      • 2022-01-13
      • 2015-08-22
      相关资源
      最近更新 更多