【问题标题】:#define string with numeric define#define 带数字定义的字符串
【发布时间】:2014-01-15 11:49:49
【问题描述】:

例如,这里有一个 C 常见的#define

#define USERNAME_LEN  100
#define SCAN_FMT  "%100s"

// str is input from somewhere
char username[USERNAME_LEN + 1];
ret = sscanf(str, SCAN_FMT, username);
// check ret == 1 ? 

我们可以有类似的东西吗:

#define SCAN_FMT   "%" USERNAME_LEN "s"

当然,这个语法不是我们想要的,而是终极目标 就是将数字#define混合成字符串#define

注意:我知道我们可以这样做:

sprintf(SCAN_FMT, "%%ds", USERNAME_LEN); // char SCAN_FMT[10];

但这不是我想要的,因为它需要运行时生成, 最好是基于 ANSI-C 或 std99。

【问题讨论】:

标签: c constants c-preprocessor


【解决方案1】:

你可能喜欢这样做:

#define SCAN_FMT_STRINGIFY(max) "%"#max"s"
#define SCAN_FMT(max) SCAN_FMT_STRINGIFY(max)

#define USERNAME_MAXLEN (100)

...

  char username[USERNAME_MAXLEN + 1] = ""; /* Add one for the `0`-terminator. */
  int ret = sscanf(str, SCAN_FMT(USERNAME_MAXLEN), username);

【讨论】:

    【解决方案2】:

    您可以将预处理器指令用于此类任务。

    1.第一个指令是#允许你做这样的事情:

    #define str(x) #x
    cout << str(test);
    

    这将被翻译成:

    cout << "test";
    

    2.第二个指令是##:

    #define glue(a,b) a ## b
    glue(c,out) << "test";
    

    将被翻译成:

    cout << "test";
    

    在这里查看更多信息preprocessor

    【讨论】:

    • 缺少一块。 OP 想要字符串化一个定义的值在它被替换之后。 IIRC,这样做需要第三个#define
    • 这对你的回答并不重要,但问题被标记为 C 而不是 C++。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多