代码之家  ›  专栏  ›  技术社区  ›  Mark Tomlin

向别名函数传递变量个数的参数

  •  1
  • Mark Tomlin  · 技术社区  · 16 年前

    取一个类似printf的函数,它接受可变数量的参数,我想做的是将这些可变数量的函数传递给一个子函数,而不改变它们的顺序。例如,将printf函数别名为一个名为console的函数…

    #include <stdio.h>
    
    void console(const char *_sFormat, ...);
    
    int main () {
        console("Hello World!");
        return 0;
    }
    
    void console(const char *_sFormat, ...) {
        printf("[APP] %s\n", _sFormat);
    }
    

    举个例子 console("Hello %s", sName) ,我也希望将该名称传递给printf函数,但它必须能够继续接受数量可变的参数,就像printf已经接受的那样。

    2 回复  |  直到 16 年前
        1
  •  4
  •   Richard Pennington    16 年前

    以下是您想要的:

    #include <stdio.h>
    #include <stdarg.h>
    
    void console(const char *_sFormat, ...);
    
    int main () {
        console("Hello World!");
        return 0;
    }
    
    void console(const char *_sFormat, ...) {
        va_list ap;
        va_start(ap, _sFormat);
        printf("[APP] ");
        vprintf(_sFormat, ap);
        printf("\n");
        va_end(ap);
    }
    
        2
  •  2
  •   Kornel Kisielewicz    16 年前

    还有一个问题(由gf指出)——您可能应该将字符串连接到 printf 以及 _sFormat 参数——我怀疑 普林特 是递归的——因此不会读取第一个参数中的格式语句!

    因此,这样的解决方案可能会更好:

    #include <stdarg.h>
    
    void console(const char *_sFormat, ...)
    {
      char buffer[256];
    
      va_list args;
      va_start (args, _sFormat);
      vsprintf (buffer,_sFormat, args);
      va_end (args);
    
      printf("[APP] %s\n", buffer);
    }
    

    使用的类型/功能:

    推荐文章