如何在一行上连接多个 C 字符串?

新手上路,请多包涵

C# 有一个语法特性,你可以在一行中将许多数据类型连接在一起。

 string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;

C ++中的等价物是什么?据我所见,您必须在单独的行中完成所有操作,因为它不支持使用 + 运算符的多个字符串/变量。这没关系,但看起来不那么整洁。

 string s;
s += "Hello world, " + "nice to see you, " + "or not.";

上面的代码会产生错误。

原文由 Nick Bolton 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 452
2 个回答
#include <sstream>
#include <string>

std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();

看看 Herb Sutter 的这篇 Guru Of The Week 文章: Manor Farm 的字符串格式化程序

原文由 Paolo Tedesco 发布,翻译遵循 CC BY-SA 2.5 许可协议

带有使用 lambda 函数的简单预处理宏的 Stringstream 看起来不错:

 #include <sstream>
#define make_string(args) []{std::stringstream ss; ss << args; return ss;}()

接着

auto str = make_string("hello" << " there" << 10 << '$');

原文由 asikorski 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题