【3FS】fmt库

fmt

fmt库地址:https://github.com/fmtlib/fmt

fmt输出:

#include <fmt/core.h>

int main() {
    std::string name = "龙龙米";
    int age = 25;

    fmt::print("你好,{}!你今年 {} 岁。\n", name, age);
    return 0;
}

格式化浮点数:

double pi = 3.14159265;
fmt::print("π ≈ {:.2f}\n", pi);  // 输出:π ≈ 3.14

使用 fmt::format() 生成字符串:

std::string message = fmt::format("你好,{}!", "龙龙米");

 

fmt::format_to 是 C++ 中 fmt 库(也称为 fmtlib)提供的一种格式化输出到迭代器的函数,它是 fmt::format 的低层版本,常用于:

  • 输出到 std::stringback_inserter

  • 自定义的缓冲区

  • 更高性能场景中避免中间字符串构造

template <typename OutputIt, typename... Args>
OutputIt format_to(OutputIt out, format_string<Args...> fmt, Args&&... args);
  • OutputIt:输出迭代器,比如 std::back_inserter
  • fmt:格式字符串
  • args:格式参数
#include <fmt/core.h>
#include <string>
#include <iterator>

int main() {
    std::string s;
    fmt::format_to(std::back_inserter(s), "Hello {}!", "world");
    // s == "Hello world!"
}

 

fmt::ptr 是 C++ 中 {fmt} 库 提供的一个辅助函数,用于 以十六进制格式安全地打印指针地址,避免指针类型转换引发的问题或打印格式不一致。

#include <fmt/core.h>
#include <fmt/ostream.h>

int main() {
    int x = 42;
    int* ptr = &x;

    fmt::print("Pointer address: {}\n", fmt::ptr(ptr));
}

输出:

Pointer address: 0x7ffeefbff4ac

 

posted @ 2021-12-29 22:49  苏格拉底的落泪  阅读(51)  评论(0)    收藏  举报