格式化生成字符串的其他方式

格式化生成字符串

除了sprintf函数,c++中还可以使用的格式化字符串方式。

boost库

#include<boost/format.hpp>

std::string s1("qwer");
char c1 = 't';
int a1 = 5;

boost::format wor = boost::format("world%1%hello %3%%2%%4%")%2022%s1%c1%a1;
//或者
boost::format wor = boost::format("%.3f " "%s " "%c " "%05d ")%d1%s1%c1;
wor %a1;

std::string s = wor.str();
std::cout << wor << "\tsize=" << wor.size() << std::endl;
//打印结果为:
//world2022hello tqwer5	size=21

//指定格式
boost::format wor = boost::format("%.3f " "%s " "%c " "%05d ") %d1 %s1 %c1 %a1;
//以上空格都可加可不加
//wor.str()为  2.300 qwer t 00005

string字符串流

#include<sstream>
#include<iostream>

std::stringstream ss1;
ss1 << "hello " << hhh << std::endl;
std::cout << ss1.str();

fmt库

https://github.com/fmtlib/fmt
可以看到readme中的介绍:Implementation of C++20 std::format

如果使用c++20的标准,可以包含format头文件,将fmt::format替换为std::format

按照fmt文档的说法,fmt方式的效率比以上两种都高

安装

#编译安装fmt库
git clone https://github.com/fmtlib/fmt.git
cd fmt
mkdir build
cd build
cmake ..
make
sudo make install

查看

fmt --version
#可以查看当前安装的fmt版本

使用

源码

#include<fmt/format.h>

int main() {
    int hhh = 10;
    double d1 = 6;
    std::string s = fmt::format("The answer {} not {}and{:.5f}", 42, hhh, d1);
    fmt::print("{}\n", s);
    //打印结果:
    //The answer 42 not 10and6.00000
  
  
    std::string ss = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
    // ss == "I'd rather be happy than right."
}

还可以设置颜色、编译时检查格式、打印容器、适配时间格式等,具体参考源码内的README.rst

编译代码,需要链接fmt库

g++ -o main main.cpp -lfmt
或者在CMakeLists.txt里
target_link_libraries(main -lfmt)
posted @ 2022-02-10 15:24  WuYunTaXue  阅读(79)  评论(0编辑  收藏  举报