格式化生成字符串的其他方式
格式化生成字符串
除了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)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂
· 凌晨三点救火实录:Java内存泄漏的七个神坑,你至少踩过三个!