将可变数量的参数传递给别名函数

发布于 2024-08-20 00:57:17 字数 446 浏览 2 评论 0原文

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

Take a function like printf that accepts a variable number of arguments what I would like to do is pass these variable number of functions to a sub function without changing their order. An example of this would be aliasing the printf function to a function called 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);
}

If I did for example console("Hello %s", sName), I would want the name to be passed to the printf function also, but it has to be able to continue to accept a varable number of arguments like the printf already does.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜是你 2024-08-27 00:57:17

这就是你想要的:

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

Here's what you want:

#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);
}
你丑哭了我 2024-08-27 00:57:17

还有另一个问题(由 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);
}

使用的类型/函数:

There'll be another problem (noted by gf) -- you should probably concatenate the string in printf and the _sFormat parameter -- I doubt that printf is recursive -- hence the format statements in the first parameter wont be read!

Hence maybe such a solution would be nicer:

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

Types/functions used:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文