C 宏预处理器在字符串中包含数字

问题描述 投票:0回答:1

我想将控制代码

x
插入字符串中,但使用十进制数字而不是十六进制(
\ux
)或八进制(
\0x
)。我很高兴有一个宏,比如 CC,这样我就可以将字符串形成为:

// Decimal 10 and 13 are ASCII LF and CR resp.
char mystring[] = "This is line 1" CC(10) CC(13) "This is line 2";

最终我想使用可能是 16 位的代码(当然超过 2 个字符)- 用于自定义打印功能,我可以在其中嵌入各种控制代码。

c macros decimal c-preprocessor
1个回答
1
投票

对于十进制数字没有通用的方法来执行此操作,但如果代码数量有限,您可以使用标记粘贴:

#include <stdio.h>

#define CC_13  "\x0D"
#define CC_10  "\x0A"

#define CC(n) CC_#n

int main(void) {
    // Decimal 10 and 13 are ASCII LF and CR resp.
    char mystring[] = "This is line 1" CC(13) CC(10) "This is line 2";

    printf("%s" CC(13) CC(10), mystring);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.