1 fmt开发环境配置
fmt是一个开源的格式化库,为C和C++提供快速、安全的字符串格式化方案。
fmt github地址:github.com/fmtlib/fmt
fmt 官网:fmt.dev/latest/inde…
1.1 下载和开发环境配置
去github或者官网下载fmt的最新版本,将压缩包解压之后,其中文件夹下的include为头文件目录,src目录为源文件目录。
在项目需要将include添加到项目的包含目录,然后在项目中将src目录下的format.cc和os.cc两个文件包含进项目中。另外src目录下还有一个fmt.cc文件,这个文件不能包含到项目中,否则会编译出错。
2 fmt的使用
fmt的格式化字符串语法与python中的str.format的语法类似,最简单一种用法如下
#include <iostream>
#include "fmt/core.h"
int main()
{
std::string s = fmt::format("The answer is {}.", 42);
std::cout << s << std::endl;
return 0;
}
另外还可以在格式化中加入位置参数,比如
#include <iostream>
#include "fmt/core.h"
int main()
{
std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
std::cout << s << std::endl;
return 0;
}
也可以使用fmt::arg传递命名参数,比如
#include <iostream>
#include "fmt/core.h"
int main()
{
std::string s = fmt::format("Hello, {name}! The answer is {number}. Goodbye, {name}.",
fmt::arg("name", "World"), fmt::arg("number", 42));
std::cout << s << std::endl;
return 0;
}