Is there a C macro to generate a repeating string?

Suppose I want to generate ------, only c -, is there a C macro to generate a repeating string?

+4
source share
3 answers

use boost for example

#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;
}
+13
source

Yes and no. This is not a simple, but not generally a good idea, but you can do it for finite, constant sizes and for constant characters. There are many ways to do this with the C preprocessor. Here is one of them:

#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;
}

, , () . n 'c' DUP ( ). Boost.Preprocessor , (ab) C/++, . Boost ++, 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;
}

, memset, @Jack.

+6

Not in the C standard. You need to write your own implementation.

EDIT:

something like that:

#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;
}
+5
source

All Articles