1

采用像 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 已经接受的那样继续接受可变数量的参数。

4

2 回答 2

4

这就是你想要的:

#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);
}
于 2010-02-05T11:36:08.260 回答
2

还有另一个问题(由 gf 指出)——您可能应该将字符串printf_sFormat参数连接起来——我怀疑这printf是递归的——因此不会读取第一个参数中的格式语句!

因此,也许这样的解决方案会更好:

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

使用的类型/功能:

于 2010-02-05T11:23:09.590 回答