The simulation implements printf function output as follows, ' d ' output shaping, ' C ' output character type, ' s ' output string, other output in its own form
my_printf ("dc\ts\ndc\ndc\ts!", 1, ' B ', "Zhangweina", 2, ' I ', 3, ' t ', "Welcome to You");
Some small knowledge of the mutable parameter list:
Macro Stdard.h
Va_list declaring a type
Va_start The first argument is the name of the va_list variable, and the second argument is the last named argument before the ellipsis.
Used to initialize a variable and set it to the first parameter in the variable parameter section.
Va_arg The first argument is the name of the va_list variable, and the second argument is the type of the variable parameter.
Called once, it points to the next mutable parameter. The type of the return value is the type of the second parameter.
Va_end accesses the last parameter and calls Va_end.
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h>//custom output functions, Output character, string, number void my_printf (const char *str, int len, ...) in alphabetical order by Str. {Va_list arg; va_start (Arg, len); for (int i = 0; i < len; i++,*str++) {char a = 0;char *a1 = null;int a2 = 0 ;//multi-branch statement, switch (*STR) {case ' C ': //parameter is character type, char type A = va_arg (ARG, char);p Utchar (a);break;case ' s ': //parameter is a string, char* type A1 = va_arg (arg,char*) ;while (*A1) {Putchar (*A1); *a1++;} break;case ' d ': //parameter is shaping, int type a2 = va_arg (arg, int);p Utchar (a2+ ' 0 '); The break;default: //parameter is other, Output Putchar (*STR) in the original form; Va_end (ARG);} Int main () {char *str = "dc\ts\ndc\ndc\ts!"; Int len = strlen (str); my_printf (str, len,1, ' B ', "Zhangweina",2, ' I ', 3, ' t ', ' welcome to you '); System ("Pause");return 0;}
This article is from the "Na-dimensional Snow" blog, please be sure to keep this source http://1536262434.blog.51cto.com/10731069/1711528
The "C language" simulation implements printf, which requires features: my_printf ("dc\ts\ndc\ndc\ts!", ...)