【问题标题】:Filling after quoted value in fmt在 fmt 中引用值后填充
【发布时间】:2022-12-29 12:29:23
【问题描述】:

我想用 C++ fmt 在引用值后填充。 我知道我可以一步完成引用,然后将 fmt 与一个参数一起使用,但我认为这样做速度较慢,而且从可读性的角度来看,我想一次性完成。 我有这个solution

但这似乎有点笨拙,我正在手动进行对齐计算,以考虑到我在值周围引用的事实......

#include <array>
#include <string>
#include <iostream>
#include <fmt/format.h>



void write_padded(const int i,char* data) {
    // note: - format_to_n will not zero termiante if out of space
    //       - use '^' as a fill char for visibility
    auto result = fmt::format_to_n(data,7, R"("{}{:^<5})",i,'\"');
    *result.out = '\0';
}


int main() {
    // space for 5 digits, 2 quotes \0
    std::array<char, 8> data{};
    write_padded(1, data.data());
    std::cout << data.data() << std::endl;
    write_padded(10, data.data());
    std::cout << data.data() << std::endl;
    write_padded(123456789, data.data());
    std::cout << data.data() << std::endl;
    write_padded(54321, data.data());
    std::cout << data.data() << std::endl;    
}

这似乎可行,但我想在不手动计算 width 的情况下执行此操作。也许还有更好的格式字符串。

注意:我知道整数可以超过 5 位数字并且幻数是不好的,但即使使用命名变量我仍然需要进行计算。

【问题讨论】:

    标签: c++ c++20 fmt


    【解决方案1】:

    您可以编写一个引用的格式化程序,例如:

    #include <fmt/format.h>
    
    struct quoted {
      int value;
    };
    
    template <>
    struct fmt::formatter<quoted> : formatter<string_view> {
      auto format(quoted q, format_context& ctx) const {
        auto buf = fmt::memory_buffer();
        fmt::format_to(std::back_inserter(buf), ""{}"", q.value);
        return formatter<string_view>::format({buf.data(), buf.size()}, ctx);
      }
    };
    
    int main() {
      fmt::print("{:^<7}
    ", quoted{1});
    }
    

    这打印

    "1"^^^^
    

    https://godbolt.org/z/Gs5qPTT13

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 2013-07-17
      • 2018-07-27
      相关资源
      最近更新 更多