Use stdarg. h to implement simple printf (variable length parameter), stdarg. hprintf
This mainly enables stdarg. h to support variable parameters.
The key steps are as follows:
1. Define a va_list variable ap.
2. initialize the ap so that it points to the first parameter in the variable parameter table.
3. Use va_arg to obtain the value of the specified type.
4. Call va_end to disable the ap pointer.
The Code is as follows:
# Include <stdio. h> # include <stdarg. h> void testprintf (char * fmt ,...) {va_list ap;/* points to each unnamed arg in turn */char * p, * sval; int ival; double dval; va_start (ap, fmt ); /* make ap point to 1st unnamed arg */for (p = fmt; * p; p ++) {if (* p! = '%') {Putchar (* p); continue;} switch (* ++ p) {case 'D': ival = va_arg (ap, int ); printf ("% d", ival); break; case 'F': dval = va_arg (ap, double); printf ("% f", dval); break; case's ': for (sval = va_arg (ap, char *); * sval; sval ++) putchar (* sval); break; default: putchar (* p ); break ;}} va_end (ap);/* clean up when done */} int main () {minprintf ("haha % s", "12345"); return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.