Format specifiers for uint8_t, uint16_t, ...?

According to 7.19.6 Formatted input/output functions of ISO/IEC 9899:TC2, there are no such format specifiers (so I doubt there any for C++2003). Even though there are some #define-macros available in C99's inttypes.h, cinttypes and inttypes.h are not part of the current standard. Of course, fixed-size integer types are non-standard as well.

Anyways, I seriously recommemend using streams instead:

<any_type> x;
f >> x;

and be done. E.g.:

std::stringstream ss;
uint32_t u;
std::cin >> u;

This has the advantage that one time in the future, changing the type of the variable does not cause a cascade of subtle bugs and undefined behaviour.


They are declared in <inttypes.h> as macros: SCNd8, SCNd16, SCNd32 and SCNd64. Example (for int32_t):

sscanf (line, "Value of integer: %" SCNd32 "\n", &my_integer);

Their format is PRI (for printf)/SCN (for scan) then o, u, x, X d, i for the corresponding specifier then nothing, LEAST, FAST, MAX then the size (obviously there is no size for MAX). Some other examples: PRIo8, PRIuMAX, SCNoFAST16.

Edit: BTW a related question asked why that method was used. You may find the answers interesting.


As others said, include <stdint.h> header that defines the format macros. In C++, however, define __STDC_FORMAT_MACROS prior to including it. From stdint.h:

/* The ISO C99 standard specifies that these macros must only be
   defined if explicitly requested.  */
#if !defined __cplusplus || defined __STDC_FORMAT_MACROS

Tags:

C++

C++11

Scanf