【fmt】fmt简介及例程

简介

{fmt}是一个开源的文本格式库,用以替代C的stdio和C++的iostreams。
{fmt}是在benchmarked排行中最快的方法, 比printf还快20%。
Speed tests:

LibraryMethodRun Time, s
libcprintf0.91
libc++std::ostream2.49
{fmt} 9.1fmt::print0.74
Boost Format 1.80boost::format6.26
Folly Formatfolly::format1.87

参考资料

fmt官方仓库
格式速查
format库官网

环境配置

  • wget https://github.com/fmtlib/fmt/archive/6.0.0.tar.gz
  • tar -zxvf 6.0.0.tar.gz
  • cd fmt-6.0.0/
  • mkdir build
  • cd build/
  • cmake …
  • sudo make
  • sudo make install

例程



#include <fmt/core.h>
#include <iostream>
#include <string>
#include <fmt/chrono.h>
#include <vector>
#include <fmt/ranges.h>
#include <fmt/color.h>
#include <fmt/ostream.h>
using namespace std;
int main() {
    //格式化输出
    fmt::print("Hello, world!\n");
    //格式字符串
    std::string s = fmt::format("The answer is {}.",42);
    cout << s << endl;
    //保留两位小数
    s = fmt::format("The answer is {:.2f}",1.12345678);
    cout << s << endl;
    //使用位置参数
    s = fmt::format("I'd rather be {1} than {0}.","right", "happy");
    cout << s << endl;
    //使用别名参数
    fmt::print("Hello, {name}!The answer is {number}.Goodbye, {name}.\n",fmt::arg("name", "world"), fmt::arg("number", 42));
    //时间格式化,需要加上#include <fmt/chrono.h>
    fmt::print("Default format: {} {}\n", 42s, 100ms);
    fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min +30s);
    //输出列表,需要加上#include <vector>    #include <fmt/ranges.h>
    std::vector<int> v = {1, 2, 3};
    fmt::print("{}\n", v);
    //输出到文件,需要加上#include <fmt/os.h>,不知道为什么没有这个头文件
    // auto out = fmt::output_file("fmt_test.txt");
    // out.print("Don't {}", "Panic");
    //输出带颜色到控制台    需要加上fmt/color.h
    fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "Hello, {}!\n", "world");
    fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | fmt::emphasis::underline, "Hello, {}!\n", "mmp");
    fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, "Hello, {}!\n", "world");
}

编译运行

编译
  • g++ FMTtest.cpp -lfmt -o FMTtest
运行结果
Hello, world!
The answer is 42.
The answer is 1.12
I'd rather be happy than right.
Hello, world!The answer is 42.Goodbye, world.
Default format: 42s 100ms
strftime-like format: 03:15:30
{1, 2, 3}
Hello, world!
Hello, mmp!
Hello, world!
(最后这三个实际颜色样式是不同的,但在这里无法显示)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值