1. fmt 库介绍
fmt 是一个现代的 C++ 字符串格式化库,提供了高效、易用且类型安全的格式化功能。它的设计灵感来源于 Python 的 str.format(),并支持 C++20 的 std::format。fmt 库的性能优于传统的 printf 和 iostream,并且具有更好的类型安全性。
2. 安装和配置
-
获取库
- GitHub: fmtlib/fmt
- 包管理器:
- vcpkg: vcpkg install fmt
- Conan: conan install fmt/8.0.1
-
包含头文件
#include <fmt/core.h> // 核心功能
#include <fmt/format.h> // 格式化功能
#include <fmt/ostream.h> // 支持流操作
#include <fmt/ranges.h> // 支持容器格式化
- 编译
确保编译器支持 C++11 或更高版本,并链接 fmt 库:
g++ -std=c++11 -o my_program my_program.cpp -lfmt
3. 基本用法
- 简单格式化
使用 fmt::format 格式化字符串:
#include <fmt/core.h>
int main() {
std::string message = fmt::format("Hello, {}!", "world");
fmt::print("{}\n", message); // 输出: Hello, world!
return