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

前端 未结 9 2579
醉梦人生
醉梦人生 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条回答
  •  萌比男神i
    2020-12-07 14:57

    Since you're using C++, why not use IOStreams? That should compile without warnings and do the right type-aware thing, as long as you're not using a brain-dead C++ implementation that doesn't define an operator << for size_t.

    When the actual output has to be done with printf(), you can still combine it with IOStreams to get type-safe behavior:

    size_t foo = bar;
    ostringstream os;
    os << foo;
    printf("%s", os.str().c_str());
    

    It's not super-efficient, but your case above deals with file I/O, so that's your bottleneck, not this string formatting code.

提交回复
热议问题