代码之家  ›  专栏  ›  技术社区  ›  Andrei Ciobanu

生成printf格式字符串的C宏

  •  4
  • Andrei Ciobanu  · 技术社区  · 15 年前

    例如。

    #define STR_FMT(x) ...code-here...
    

    STR_FMT(10) "%10s"

    STR_FMT(15) 扩展到 "%15s"

    ...

    以便在printf中使用此宏:

    printf(STR_FMT(10), "*");
    
    2 回复  |  直到 10 年前
        1
  •  11
  •   Community Mohan Dere    9 年前

    你可以,但我想最好是利用这个能力 printf() 必须动态指定字段大小和/或精度:

    #include <stdio.h>
    
    int main(int argc, char* argv[])
    {
        // specify the field size dynamically
        printf( ":%*s:\n", 10, "*");
        printf( ":%*s:\n", 15, "*");
    
        // specify the precision dynamically
        printf( "%.*s\n", 10, "******************************************");
        printf( "%.*s\n", 15, "******************************************");
    
        return 0;
    }
    


    如果您决定改用宏,请使用 # 间接经营者(和 ## 接线员,如果你在其他地方使用)比如:

    // macros to allow safer use of the # and ## operators
    #ifndef STRINGIFY
    #define STRINGIFY2( x) #x
    #define STRINGIFY(x) STRINGIFY2(x)
    #endif
    
    #define STR_FMTB(x) "%" STRINGIFY(x) "s"
    

    否则,如果决定使用宏指定字段宽度,将出现不希望的行为(如 What are the applications of the ## preprocessor operator and gotchas to consider?

        2
  •  7
  •   Armen Tsirunyan    15 年前
    #define STR_FMT(x) "%" #x "s"