Correct way to use scanf / printf (and family) with fixed size types?

前端 未结 2 1550
忘掉有多难
忘掉有多难 2020-12-16 13:47

Reading this SO question, I started wondering - what is the correct way to use scanf/printf (and family) with fixed size types?

For example

相关标签:
2条回答
  • 2020-12-16 14:10

    The correct way is to use inttypes.h which defines standard macros for printf family and the scanf family, e.g.

    printf ("%" PRId16, short_int);
    scanf ("%" SCNd16, &short_int);
    
    0 讨论(0)
  • 2020-12-16 14:19

    The inttypes.h header file contains macros that define the correct format specifiers for fixed-width integers defined in stdint.h. For example, the type specifier for printf() and int16_t is the macro named PRId16. Example:

    int16_t x;
    scanf("%" SCNd16, &x);
    
    printf("You have entered: %" PRId16 "\n", x);
    
    0 讨论(0)
提交回复
热议问题