c++ - 如何在boost库中格式化字符串

标签 c++ boost

我想在 C++ 中使用 boost 库格式化字符串。我正在做如下。

std::string msg = "Version: %1. Version %2.";
boost::format formatter(msg.c_str());
formatter % "v1" % "v2";
xyz_function(msg);

我们可以在一个语句中使用 sprintf 做到这一点,那么有没有一种方法可以优化上述 boost 实现以在一个语句或其他语句中形成字符串?

提前致谢。

最佳答案

boost::format 对象可以转换为字符串,它也有显式转换函数。

boost::format fmt
    = boost::format("Luke %1% and Han %2%.") % "Skywalker" % "Solo";

因此可以使用其中任何一个:

  • std::string fmtStr = boost::str(fmt);
  • std::string fmtStr = fmt.str();

参见 example and demonstration , 和 Boost Library Format; getting std::string对于 boost::str 提示。

关于c++ - 如何在boost库中格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45211807/

相关文章:

c++ - 看似成员函数声明前的 Class 关键字

c++ - 在 VC++ 2010 项目中使用 Boost 序列化库

c++ - 我应该如何初始化 boost::array?

c++ - 理解模板的构造函数初始值设定项的解析

c++ - 通过变量(字符串)调用对象和方法

c++ - 非模板函数上的约束表达式有什么意义?

c++ - 在 Xcode [c++] 中的 assert (assert.h) 中定义 lambda 时,为类似函数的宏调用编译错误提供了太多参数

c++ - 为什么我不能转发声明 typedef?

c++ - 振奋 spirit 2 : is there a way to know what is the parser progression percentage?

c++ - 海龟模型 : MOCK_EXPECT fails if mocked class method returns a value