Clean code to printf size_t in C++ (or: Nearest equivalent of C99's %z in C++)

前端 未结 9 2575
醉梦人生
醉梦人生 2020-12-07 14:20

I have some C++ code that prints a size_t:

size_t a;
printf(\"%lu\", a);

I\'d like this to compile without warnings on both 32

9条回答
  •  春和景丽
    2020-12-07 15:11

    The fmt library provides a fast portable (and safe) implementation of printf including the z modifier for size_t:

    #include "fmt/printf.h"
    
    size_t a = 42;
    
    int main() {
      fmt::printf("%zu", a);
    }
    

    In addition to that it supports Python-like format string syntax and captures type information so that you don't have to provide it manually:

    fmt::print("{}", a);
    

    It has been tested with major compilers and provides consistent output across platforms.

    Disclaimer: I'm the author of this library.

提交回复
热议问题