c++ - 带有 C++ 字符串类的 sprintf

标签 c++ std

我非常喜欢 sprintf in c++? 中给出的答案但这仍然不是我要找的东西。

我想创建一个带有占位符的常量字符串,比如

const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout";

然后使用可替换参数构建字符串,例如:

sprintf(url, LOGIN_URL, protocol, server); //coding sprintf from long ago memory, please ignore

但如果可以的话,我真的想远离 C 字符串。

stringbuilder() 方法要求我将我的常量字符串分块并在我想使用它们时组装它们。这是一个很好的方法,但我想做的更简洁。

最佳答案

Boost format library听起来像您正在寻找的内容,例如:

#include <iostream>
#include <boost/format.hpp>

int main() {
  int x = 5;
  boost::format formatter("%+5d");
  std::cout << formatter % x << std::endl;
}

或者对于您的具体示例:

#include <iostream>
#include <string>
#include <boost/format.hpp>

int main() {
  const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout";

  const std::string protocol = "http";
  const std::string server = "localhost";

  boost::format formatter(LOGIN_URL);
  std::string url = str(formatter % protocol % server);
  std::cout << url << std::endl;
}

关于c++ - 带有 C++ 字符串类的 sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7583976/

相关文章:

c++ - 重载 + 运算符以添加数组

c++ - 值(value)与对象

c++ - 映射/设置迭代器在 std::map 中不可递增

c++ - if (!x) 和 if (x == nullptr) 之间有什么区别吗?

c++ - 优化编译器可以添加 std::move 吗?

c++ - Wav文件噪声去除

c++ - 如何将模板中具有非依赖名称的 msvc++ 代码移植到 Linux?

c++ - 指向 Eigen3 vector 的 std::list 的指针或引用

c++ - 没有对 std::find() 的匹配调用,尽管其他 find 语句有效,并且包含 <algorithm>

c++ - 空 std::queue 将数据推送到陈旧项目的末尾