gpt4 book ai didi

c - 打印定义名称c

转载 作者:行者123 更新时间:2023-11-30 21:14:43 24 4
gpt4 key购买 nike

#define Page 5

void printSystemInfo() {

printf ("%i", Page);
}

这就是我的代码,谁能解释一下如何在控制台中打印第 5 页?

现在我的控制台看起来像“5”,但我想要“Page 5”

感谢您的帮助!

最佳答案

您可以使用一些预处理器技巧。我们有 # 运算符,它将符号转换为字符串。

#define _(a)    #a

当您调用_(foo)时,它会将其翻译为“foo”。因此,就您的情况而言,您可以执行以下操作:

#include <stdio.h>

#define _(a) # a
#define PAGE 5

int main(int argc, char *argv[])
{
printf("%s: %i\n", _(PAGE), PAGE);
return 0;
}

这将做什么:

  1. 我们定义了一个名为 _ 的宏,它接受一个参数 a。该宏使用预处理器中的运算符 # (称为 stringification )。这会将传递给宏的命名转换为字符串。示例:_(foo) 被翻译为 "foo"

  2. main 中,printf() 调用随后被翻译为 printf("%s: %i\n", "PAGE",5);。逐步地,当预处理器看到 _(PAGE) 符号时,它会将其翻译为 "PAGE"

  3. 上面的链接解释了这个东西的内部工作原理,我引用了它(我的标记):

Sometimes you may want to convert a macro argument into a string constant. Parameters are not replaced inside string constants, but you can use the ‘#’ preprocessing operator instead. When a macro parameter is used with a leading ‘#’, the preprocessor replaces it with the literal text of the actual argument, converted to a string constant. Unlike normal parameter replacement, the argument is not macro-expanded first. This is called stringification.

关于c - 打印定义名称c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com