如何字符串化C中的前pression [英] How to stringify an expression in C
本文介绍了如何字符串化C中的前pression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法来评价在C字符串化之前前pression?
Is there a way to evaluate an expression before stringification in c?
例如:
#define stringify(x) #x
...
const char * thestring = stringify( 10 * 50 );
问题是,我想获得
The problem is that I want to get
const char * thestring = "500";
和不的:
const char * thestring = "10 * 50";
可以这样做?
推荐答案
的C preprocessor不能做到这一点,所以使用的snprintf
而不是:
The C preprocessor cannot do that, so use snprintf
instead:
char *stringify(int n) {
char *res = malloc(12);
snprintf(res, 12, "%d", n);
return res;
}
用法
const char *thestring = stringify(10 * 50);
NB
为了简便起见,我省略了错误控制和免费
。
这篇关于如何字符串化C中的前pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文