fmt 教程¶
安装编译¶
注意:fmt 可以以加载 lib 库形式使用或者仅仅包含头文件,若包含头文件使用需要额外包含 src 目录下文件 - fmt 源码目录如下
├─.github
├─doc
├─include
├─src
├─support
└─test
头文件包含使用¶
- 将 src 目录及其子文件移动到 include 目录下
- 在项目中包含 include 项目,如 vs 中操作: 项目 ->右键属性 ->c++->附加包含目录 ->键入 fmt include 路径
- 项目中使用 fmt 前包含头文件
#include<src/format.cc>
、#include<fmt/core.h>
和其它所需要头文件
注意:头文件 #include<src/format.cc>
一定要包含
#include<fmt/core.h>
//不是用lib则需要额外包含src目录下format.cc文件,否则会编译报错
#include<src/format.cc>
int main()
{
std::string str = fmt::format("hello {}!", "world");
fmt::print("hello {}!", "world");
}
编译 lib 使用¶
- 编译 lib 库
- 进入 fmt 项目,执行以下指令
mkdir build&&cd build
make ..
- 如果是 windows 且安装 vs,则会在 build 目录下生成 FMT.sln 文件,使用 vs 打开
- 进入 FMT 项目,在 fmt 项目上点击生成,将会生成 lib 文件
- 使用 lib 库
- 在项目中包含 include 路径
- 载入 lib 库,
#pragma comment(lib,"../lib/fmtd.lib")
- 包含头文件
#include<fmt/core.h>
以及其它所需要文件
#pragma comment(lib,"../lib/fmtd.lib")
#include<fmt/core.h>
int main()
{
std::string str = fmt::format("hello {}!", "world");
fmt::print("hello {}!", "world");
}
入门¶
- fmt::format 格式化字符串
- fmt::print 打印到标准输出
- fmt 使用花括号
{}
来代替一个可插入字符串
#include<fmt/core.h>
#include<src/format.cc>
int main()
{
//花括号中可选填0 1 2...用来标记参数索引
fmt::print("{},{}{}", "hello", "world", "!");
fmt::print("{0},{1}{2}", "hello", "world", "!");
fmt::format("{},{}{}", "hello", "world", "!");
}
基础¶
- fmt 有一系列的格式化标志,详见 官方文档
进阶¶
- fmt 支持自定义格式化器,详见 官方文档