On Sun, 09 Jan 2005 19:15:07 GMT in comp.lang.c++, "tings"
How to write such a function that can take varible number and tyoes of
arguments, like printf("... %d, %s...", myInt, myString...)?
/* VA_EXAMP.C - variable argument function example, subset of printf() */
/* Released to public domain by author, David Harmon, Oct 1993 */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
void va_example(char *format, ...)
{
va_list ap;
char ch;
va_start(ap, format);
/* Note: because of default promotions, you can't use char,
or float types with va_arg. Use int or double instead. */
while ((ch = *format++) != 0) {
if (ch != '%')
fputc(ch, stdout);
else {
if ((ch = *format++) == 0)
break;
switch (ch) {
case 'd': {
int arg = va_arg(ap, int);
char buf[10];
itoa( arg, buf, 10);
fputs( buf, stdout);
break;
}
case 'c': {
int arg = va_arg(ap, int);
fputc( (char)arg, stdout);
break;
}
case 's': {
char *arg = va_arg(ap, char *);
fputs(arg, stdout);
break;
}
default:
fputc('%', stdout);
fputc(ch, stdout);
}
}
}
va_end(ap);
}
int main(void)
{
va_example("\"%s\" is a string, %c is a char, and %d is an integer.\n",
"Who is John Galt?", '$', -1);
return 0;
}