[英]Pass a variable number of arguments to an aliased function
像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一样继续接受大量的参数。 。
这就是您想要的:
#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);
}
会有另一个问题(由gf指出)-您可能应该将printf
和_sFormat
参数中的字符串连接_sFormat
-我怀疑printf
是否是递归的-因此不会读取第一个参数中的format语句!
因此,也许这样的解决方案会更好:
#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);
}
使用的类型/功能:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.