Is there a C macro to generate repeat string? [dup

2020-02-12 07:12发布

Suppose I want to generate ------, with only -, is there a C macro to generate repeated string ?

标签: c++ c macros
3条回答
不美不萌又怎样
2楼-- · 2020-02-12 07:56

use boost, E.g

#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;
}
查看更多
贼婆χ
3楼-- · 2020-02-12 08:03

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

EDIT:

something like this:

#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;
}
查看更多
对你真心纯属浪费
4楼-- · 2020-02-12 08:11

Yes and no. It's not simple, and 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:

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

It's not pretty, and only useful when you really want the string to be stored as static (constant) data. Both the n and 'c' parameters to DUP have to be a constants (they cannot be variables). The Boost.Preprocessor module has a lot of good information for how and when to (ab)use the C/C++ preprocessor like this. Although Boost is a C++ library, the preprocessor information is largely applicable to straight C.

In general, you're much better off doing this in normal C code:

/* 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;
}

or, use memset, as @Jack suggested.

查看更多
登录 后发表回答