fmt示例

fmt/11.1.1

#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/chrono.h> //更复杂的格式,如日期和时间,可以使用 fmt/chrono.h 头文件:
#include <fmt/ranges.h> //对于容器,如 std::vector,可以使用 fmt/ranges.h 头文件
#include <fmt/ostream.h>
#include <fmt/compile.h>
#include <fmt/color.h>

#include <stdexcept>
#include <iostream>
#include <vector>
#include <fstream>
// 递归终止函数
void print_formatted(const char* format_str) {
    std::cout << fmt::format("{}", format_str);
}
// 递归函数,处理参数包
template <typename T, typename... Args>
void print_formatted(const char* format_str, T&& first, Args&&... args) {
    std::size_t pos = std::string_view(format_str).find("{}");
    if (pos == std::string_view::npos) {
        std::cerr << "Invalid format string.\n";
        return;
    }
    std::string_view prefix = format_str;
    prefix.remove_suffix(std::string_view(format_str).size() - pos);
    std::cout << fmt::format("{}", prefix);
    std::cout << fmt::format("{}", std::forward<T>(first));
    // 当还有更多参数时继续递归,否则调用终止函数
    if constexpr (sizeof...(args) > 0) {
        print_formatted(std::string_view(format_str).substr(pos + 2).data(), std::forward<Args>(args)...);
    } else {
        print_formatted(std::string_view(format_str).substr(pos + 2).data());
    }
}

struct Person {
    std::string name;
    int age;
};

template <>
struct fmt::formatter<Person> {
    // 解析格式说明符
    constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
        return ctx.end();
    }
    // 格式化 Person 对象
    template <typename FormatContext>
    auto format(const Person& p, FormatContext& ctx) const -> decltype(ctx.out()) {
        return fmt::format_to(ctx.out(), "{} ({} years old)", p.name, p.age);
    }
};


int main() {
    // 格式化字符串
    std::string message = fmt::format("Hello, {}!", "World");
    std::cout << message << std::endl;

    // 格式化数字
    int num = 42;
    std::string num_str = fmt::format("The answer is {}.", num);
    std::cout << num_str << std::endl;

    // 格式化浮点数
    double pi = 3.141592653589793;
    std::string pi_str = fmt::format("Pi is approximately {:.2f}.", pi);
    std::cout << pi_str << std::endl;

    // 格式化多个参数
    std::string multi_str = fmt::format("{} plus {} is {}.", 2, 3, 5);
    std::cout << multi_str << std::endl;

    // 格式化对齐和填充
    std::string align_str = fmt::format("{:>10} | {:<10}", "left", "right"); //将 "left" 右对齐,总宽度为 10,将 "right" 左对齐,总宽度为 10,使用 | 分隔。
    std::cout << align_str << std::endl;

    // 格式化十六进制数
    int hex_num = 255;
    std::string hex_str = fmt::format("The hexadecimal value of 255 is {:x}.", hex_num);
    std::cout << hex_str << std::endl;

    // 使用 fmt::print 直接输出格式化的字符串,而不是先存储在变量中:
    fmt::print("Hello, {}!\n", "World");

    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    fmt::print("The current time is {:%Y-%m-%d %H:%M:%S}.\n", now);

    std::vector<int> v = {1, 2, 3, 4, 5};
    fmt::print("The vector is {}.\n", v);

    // 格式化自定义类型
    Person person{"Alice", 25};
    std::string person_str = fmt::format("{}", person);
    fmt::print("{}\n", person_str);

    //安全的文件输出
    std::ofstream file("output.txt");
    fmt::print(file, "Hello, {}!", "World");

    //编译时格式化
    fmt::print(FMT_COMPILE("The answer is {}.\n"), 42);

    //颜色输出
    fmt::print(fg(fmt::color::red) | fmt::emphasis::bold, "This is a bold red text.\n");
    fmt::print(fg(fmt::color::yellow_green) | fmt::emphasis::bold, "This is a bold blue text.\n");

    //格式化错误消息
    try {
        throw std::runtime_error(fmt::format("Error occurred at line {}.", 42));
    } catch (const std::runtime_error& e) {
        fmt::print(stderr, "Caught exception: {}\n", e.what());
    }

    //格式化字符串连接
    std::vector<std::string> parts = {"Hello", "World", "!"};
    std::string joined = fmt::format("{}", fmt::join(parts, " "));
    fmt::print("{}\n", joined);

    // 可变参数模板和递归格式化
    print_formatted("-- The answer is {} and {} and {}.\n", 42, 43, 44);
    return 0;
}

posted @ 2025-01-14 17:21  料峭春风吹酒醒  阅读(43)  评论(0)    收藏  举报