Search code examples
c++fmt

How to figure out the length of the result of `fmt::format` without running it?


While answering this question about printing a 2D array of strings into a table, I realized:

I haven't found a better way to determine the length of the result of a fmt::format call that to actually format into a string and check the length of that string.

Is that by design, or is there a more efficient way to go about that? I don't know the internals of fmtlib all too well, but I imagine, the length of the result is known before memory allocation happens. I'd especially like to avoid the memory allocation.


Solution

  • Straight from the API documentation:

    template<typename ...T>  
    auto fmt::formatted_size(format_string<T...> fmt, T&&... args) -> size_t  
    

    Returns the number of chars in the output of format(fmt, args...).