是否有C宏来生成重复字符串?

dai*_*isy 5 c c++ macros

假设我要产生------,只用-,是有一个C宏来产生重复的字符串?

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)

  • 包括提升吗?就个人而言,我更喜欢做一个简单的循环. (4认同)
  • @TheMask:同意了.为什么你会为此增加编译时间(*很多*)?提升太过分了. (3认同)

sfs*_*man 6

是的,不是.它并不简单,通常不是一个好主意,但你可以用有限的,恒定的大小和恒定的字符来做.使用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建议的那样使用.


Jac*_*ack 5

不是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)