fmtlib 格式化 基本用法 3——format.h 用法

12 篇文章 0 订阅

fmtlib库的 format.h 包含诸多功能,主要是:

template<detail_exported::fixed_string Str>
constexpr auto fmt::operator""_a()
   等价于使用 fmt::arg()

template<typename T>
auto fmt::ptr(T p) -> const void*

template<typename Enum>
constexpr auto fmt::underlying(Enum e) noexcept -> underlying_t<Enum>
    将枚举转换为基础类型。

template<typename T>
auto fmt::to_string(const T &value) -> std::string
    
template<typename Range>
auto fmt::join(Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>>

template<typename T>
auto fmt::group_digits(T value) -> group_digits_view<T>
    添加千分位","

template<typename T, size_t SIZE = inline_buffer_size, typename Allocator = std::allocator<T>>
class fmt::basic_memory_buffer : public fmt::detail::buffer<T>


template<typename ...T>
auto fmt::system_error(int error_code, format_string<T...> fmt, T&&... args) -> std::system_error

void fmt::format_system_error(detail::buffer<char> &out, int error_code, const char *message)
    <message>: <system-message>

测试代码如下:

#include <iostream>
#include <vector>
#include <fmt/format.h>
using namespace std;


int main(int argc, char** argv)
{
    using namespace fmt::literals;
    fmt::print("Elapsed time: {s:.2f} seconds\n", "s"_a = 1.23);

    auto p = std::make_shared<int>(3);
    auto s = fmt::format("{}", fmt::ptr(p));
    cout << s << endl;

    std::string answer = fmt::to_string(42);
    cout << answer << endl;


    std::vector<int> v = { 1, 2, 3 };
    fmt::print("{}\n", fmt::join(v, ", "));
    // Output: "1, 2, 3"


    fmt::print("{}\n", fmt::group_digits(12345));
    // Output: "12,345"


    auto out = fmt::memory_buffer();
    format_to(std::back_inserter(out), "The answer is {}.", 42);
    cout << fmt::to_string(out) << endl;

    // This throws std::system_error with the description
    //   cannot open file 'madeup': No such file or directory
    // or similar (system message may vary).

    try {
        const char* filename = "madeup";
        std::FILE* file = std::fopen(filename, "r");
        if (!file)
            throw fmt::system_error(errno, "cannot open file '{}'", filename);
    }catch (std::exception& e) {
        cout << e.what() << endl;
    }


    return 0;
}

 运行之后的结果:

format提供了一些工具函数,比较有用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值