【问题标题】:Pass a variable number of arguments to an aliased function将可变数量的参数传递给别名函数
【发布时间】:2011-01-13 11:39:52
【问题描述】:

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

【问题讨论】:

  • 我正在使用 Visual C++ Express Edition 2008。
  • 您可能想要连接 "[APP] "_sFormat

标签: c++ variables arguments variadic-functions argument-passing


【解决方案1】:

这就是你想要的:

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

【讨论】:

  • 编译后你会得到一个加分:)。
  • 我也给了你先生,很好的答案,它工作得非常好,我可以用它来完成其他一些功能。 @Kornel Kisielewicz,你有很大的帮助。也感谢您的原始回答以及您对所做的一切解释所做的手。非常有用。
【解决方案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);
}

使用的类型/功能:

【讨论】:

  • @Mark,你忘了#include &lt;stdarg.h&gt; 吗?
  • printf() 不需要 va_list。
  • @Richard,+1,完全忘记了
  • 还需要注意 printfvprintf 基函数的存在。 (另见 Richard Thompson 的回答:stackoverflow.com/questions/2206742/…
  • @Mark - 好点。如果您害怕,请使用 vsnprintf,并将最大值传递给函数。
猜你喜欢
  • 1970-01-01
  • 2019-07-22
  • 2015-09-23
  • 1970-01-01
  • 2015-01-05
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
相关资源
最近更新 更多