[英]Converting a #defined constant number to a string
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 ? 可以使用什么预处理器技巧将MAX_STR_LEN数字转换为字符串,以便我可以在上面的scanf调用中使用它? Basically:
基本上:
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. 注意:我当然可以直接做“%100s”,但这样做会失败。 I can also do #define MAX_STR_LEN_STR "100", but I am hoping for a more elegant solution.
我也可以#define MAX_STR_LEN_STR“100”,但我希望有一个更优雅的解决方案。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.