#include <stdio.h>
#define stringify(s) tostring(s)
#define tostring(s) #s
#define MAX_VALUE 65536
#define NUM 64 * 1024
enum {
MIN_VALUE = 1024,
};
int main(int argc, char *argv[])
{
const char *max_str = stringify(MAX_VALUE);
const char *min_str = stringify(MIN_VALUE);
printf("max = %s, min = %s\n", max_str, min_str);
return 0;
}
输出为&#34; max = 65536,min = MIN_VALUE num = 1024 * 64&#34; 专家,如何修改我的代码输出如下: max = 65536,min = 1024 num = 65536
谢谢。
答案 0 :(得分:3)
MIN_VALUE是一个数字。为什么需要对其进行字符串化?
只需使用:
printf("%d\n", MIN_VALUE);
答案 1 :(得分:0)
我认为你最好不要使用函数代替宏,原因是宏只在编译时才被扩展,更不用说运行时了。
考虑这个例子:
#define stringify(V) #V
#include <stdio.h>
int main()
{
int x = 5;
const char *str = stringify(x);
printf("%s\n", str);
}
在预处理器完成它之后,代码将如下所示:
#include <stdio.h>
int main()
{
int x = 5;
const char *str = "x";
printf("%s\n", str);
}
因为所有预处理程序指令#
都这样做,所以将给定参数包装在引号中。
如果你想要一个对常量,枚举(强制转换为int)和整数变量有效的字符串行为,你可以使用sprintf
:
#include <stdio.h>
#include <stdlib.h>
char *stringify(int x)
{
/* get the length of the required buffer */
int len = snprintf(0, 0, "%i", x);
/* allocate memory */
char *res = malloc(sizeof(char) * (len + 1));
/* handle allocation failure */
if(!res)
return 0;
/* convert the int to string */
snprintf(res, len + 1, "%i", x);
/* return the result */
return res;
}
int main()
{
int x = 5;
char *str = stringify(x);
printf("%s\n", str);
/* we free the memory allocated by malloc */
free(str);
}
这将是您在C中实现这一目标的一种方式。如果您想了解我所使用的功能的更多信息,请查看:
答案 2 :(得分:0)
#define
语句,因此它基本上是一个文本替换(使用参数实际上更加智能化)。
由于stringify(s)
为#defined
,预处理器会忠实地完成它。
stringify(MAX_VALUE)
衰减到stringify(65536)
,因为MAX_VALUE #defined为65536
,也称为预处理。
但是Enumerations
是C语言本身的一部分,在预处理时不知道,
因此,stringify(MIN_VALUE)
保留为stringify(MIN_VALUE),因此toString(MIN_VALUE)
进行整数运算或打印
num = 65536
“是”,有一种方法可以使预处理器执行整数运算,即在preprocessor
条件下使用它。
#if 1024*64 == 65536
printf("num=65536\n");
#endif