BLU*_*IXY 14
使用提升,例如
#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("-", 6));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是的,不是.它并不简单,通常不是一个好主意,但你可以用有限的,恒定的大小和恒定的字符来做.使用C预处理器有很多方法可以做到这一点.这是一个:
#define DUP(n,c) DUP ## n ( c )
#define DUP7(c) c c c c c c c
#define DUP6(c) c c c c c c
#define DUP5(c) c c c c c
#define DUP4(c) c c c c
#define DUP3(c) c c c
#define DUP2(c) c c
#define DUP1(c) c
#include <stdio.h>
int main(int argc, char** argv)
{
printf("%s\n", DUP(5,"-"));
printf("%s\n", DUP(7,"-"));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它并不漂亮,只有当你真的希望将字符串存储为静态(常量)数据时才有用.两个n和"c"的参数DUP必须是一个常数(它们不能是变量).该Boost.Preprocessor模块有很多很好的信息,如何以及何时(AB)使用C/C++预处理器这样的.虽然Boost是一个C++库,但预处理器信息很大程度上适用于C语言.
一般来说,在普通的C代码中执行此操作要好得多:
/* In C99 (or C++) you could declare this:
static inline char* dupchar(int c, int n)
in the hopes that the compiler will inline. C89 does not support inline
functions, although many compilers offered (inconsistent) extensions for
inlining. */
char* dupchar(int c, int n)
{
int i;
char* s;
s = malloc(n + 1); /* need +1 for null character to terminate string */
if (s != NULL) {
for(i=0; i < n; i++) s[i] = c;
}
return s;
}
Run Code Online (Sandbox Code Playgroud)
或者,memset像@Jack建议的那样使用.
不是C标准.你需要编写自己的实现.
编辑:
这样的事情:
#include <stdio.h>
#include <string.h>
#define REPEAT(buf, size, ch) memset(&buf, ch, size)
int main(void)
{
char str[10] = { 0 };
REPEAT(str, 9, '-');
printf("%s\n", str); //---------
return 0;
}
Run Code Online (Sandbox Code Playgroud)