为返回一个串c preprocessor宏重复一定的次数 [英] C preprocessor macro for returning a string repeated a certain number of times
本文介绍了为返回一个串c preprocessor宏重复一定的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有人知道任何C99 preprocessor魔术,允许创建由另一个字符串的字符串重复n次?
Does someone know of any C99 preprocessor magic that allows for creating a string consisting of another string repeated N times?
例如
STRREP( "%s ", 3 )
变为
"%s %s %s "
在preprocessing。
after preprocessing.
我能想到自己的唯一的事情就是这样的。
The only thing I could think of myself was something like this
#define STRREP( str, N ) STRREP_##N( str )
#define STRREP_0(str) ""
#define STRREP_1(str) str
#define STRREP_2(str) str str
#define STRREP_3(str) str str str
...
效果很好,但丑,因为我必须手动定义每个重复长度的宏。我想与显示<一个复杂的宏和宏返回的宏观参数的号码一起使用href=\"http://stackoverflow.com/questions/2308243/macro-returning-the-number-of-arguments-it-is-given-in-c\">here.
推荐答案
我的建议是使用升压。
例如
#include <stdio.h>
#include <boost/preprocessor/repetition/repeat.hpp>
#define Fold(z, n, text) text
#define STRREP(str, n) BOOST_PP_REPEAT(n, Fold, str)
int main(){
printf("%s\n", STRREP("%s ", 3));//STRREP("%s ", 3) -> "%s %s %s "
return 0;
}
这篇关于为返回一个串c preprocessor宏重复一定的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文