Search code examples
c++fmt

C++ {fmt} library: Is there a way to format repeated format fields?


I have a program with many formatted write statements that I'm using the fmt library for. Some of them have many fields, say 100 for example purposes, something like this:

fmt::print(file_stream, "{:15.5g}{:15.5g}{:15.5g}/*and so on*/", arg1, arg2, arg3/*same number of arguments*/);

Is there a straightforward way to truncate the fields so they don't all have to be written out? Obviously this example wouldn't work but it illustrates the idea:

fmt::print(file_stream, 100("{:15.5g"), arg1, arg2, arg3/*etc*/);

Solution

  • You can put your arguments in an array and format part of this array as a view (using span or similar) with fmt::join (https://godbolt.org/z/bo1GrofxW):

    #include <array>
    #include <span>
    #include <fmt/format.h>
    
    int main() {
      double arg1 = .1, arg2 = .2, arg3 = .3;
      double args[] = {arg1, arg2, arg3};
      fmt::print("{:15.5}", fmt::join(std::span(args, args + 2), ""));
    }
    

    Output:

                0.1            0.2