How do you create a printf like function where the last parameters can be any number of variables?
Thanks.
How do you create a printf like function where the last parameters can be any number of variables?
Thanks.
Hmmm - not sure if I understand you here - Are you wanting to know how to make a function that will accept an 'infinite' amount of arguments?
if so, it would go something like this:
Its the ellipsis notation (the '...') that you should be concerned with - using this notation, the number of arguments passed to the function's parameter list must be equal to, or exceed, the amount of parameters given in the parameter list. This is different from a regular parmater list, as you no doubt already know, where the number of arguments passed must be the same as the number of parameters.Code:void foo( float stuff, int more_stuff, ... ) { statements declarations }
~/
Last edited by kermit; 11-17-2003 at 06:47 PM.
Okay but how would you check to see how many arguments are actually passed? And how would you access them?
You might find this helpful.
~/
Something like this maybe (not my code, it's nicked from some old site).Originally posted by tyouk
Okay but how would you check to see how many arguments are actually passed? And how would you access them?
Code:#include <stdio.h> #include <stdarg.h> void test_fn(const char *msg, const char *types, ...); int main(void) { printf("VA...TEST\n"); test_fn("PARAMETERS: 1, \"abc\", 546", "isi", 1, "abc", 546); test_fn("PARAMETERS: \"def\", 789", "si", "def", 789); return 0; } static void test_fn ( const char *msg, /* message to be printed */ const char *types, /* parameter types (i,s) */ ... ) /* variable arguments */ { va_list argument; int arg_int; char *arg_string; const char *types_ptr; types_ptr = types; printf("\n%s -- %s\n", msg, types); va_start(argument, types); while (*types_ptr != '\0') { if (*types_ptr == 'i') { arg_int = va_arg(argument, int); printf("integer: %d\n", arg_int); } else if (*types_ptr == 's') { arg_string = va_arg(argument, char *); printf("string: %s\n", arg_string); } ++types_ptr; } va_end(argument); }
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
Thanks, just so you know I am trying to make a windows function that takes in data (like a printf does) and outputs it into a desired window.
Thanks for all your help.