将#定义的常数转换为字符串

时间:2021-01-31 10:21:00

I have a constant defined:

我定义了一个常数

#define MAX_STR_LEN 100

I am trying to do this:

我试着这么做:

scanf("%" MAX_STR_LEN "s", p_buf);

But of course that doesn't work.

但这当然行不通。

What preprocessor trick can be use to convert the MAX_STR_LEN numerica into a string so I can use it in the above scanf call ? Basically:

可以使用什么预处理器技巧将MAX_STR_LEN numerica转换为字符串,以便我可以在上面的scanf调用中使用它?基本上:

scanf("%" XYZ(MAX_STR_LEN) "s", p_buf);

What should XYZ() be ?

XYZ()应该是什么?

Note: I can of course do "%100s" directly, but that defeats the purpose. I can also do #define MAX_STR_LEN_STR "100", but I am hoping for a more elegant solution.

注意:我当然可以直接使用“%100s”,但是这样做的目的是错误的。我也可以定义MAX_STR_LEN_STR“100”,但我希望有一个更优雅的解决方案。

1 个解决方案

#1


15  

Use the # preprocessing operator. This operator only works during macro expansion, so you'll need some macros to help. Further, due to peculiarities inherent in the macro replacement algorithm, you need a layer of indirection. The result looks like this:

使用#预处理操作符。此操作符只在宏展开期间工作,因此需要一些宏来帮助。此外,由于宏替换算法固有的特性,您需要一个间接层。结果是这样的:

#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)

scanf("%" STRINGIZE(MAX_STR_LEN) "s", p_buf);

#1


15  

Use the # preprocessing operator. This operator only works during macro expansion, so you'll need some macros to help. Further, due to peculiarities inherent in the macro replacement algorithm, you need a layer of indirection. The result looks like this:

使用#预处理操作符。此操作符只在宏展开期间工作,因此需要一些宏来帮助。此外,由于宏替换算法固有的特性,您需要一个间接层。结果是这样的:

#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)

scanf("%" STRINGIZE(MAX_STR_LEN) "s", p_buf);