[C Language] simulates printf. required functions: my_printf ("dc \ ts \ ndc \ ts! ",...)
The output format of the printf function is as follows: 'D' output shaping, 'C' output encoding type, and 's' output string, other output formats: my_printf ("dc \ ts \ ndc \ ts! ", 1, 'B'," zhangweina ", 2, 'I', 3, 't'," welcome to you "); some tips about variable parameter lists: // macro stdard. h // va_list declares a type. // The first parameter of va_start is the name of the va_list variable, and the second parameter is the last parameter with a name before the ellipsis. // It is used to initialize a variable and set it to the first parameter in the Variable Parameter section. // The first parameter of va_arg is the name of the va_list variable, and the second parameter is of the variable type. // Call once to point to the next variable parameter. The type of the returned value is the type of the second parameter. // Call va_end after the last parameter is accessed.
# Include <stdio. h> # include <stdlib. h> # include <stdarg. h> # include <string. h> // custom output function, which outputs characters, strings, and numbers in the string order of str my_printf (const char * str, int len ,...) {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. The switch (* str) {case 'C': // The parameter is of optimized type, char type a = va_arg (arg, char); putchar (a); break; case's ': // when the parameter is a string, char * type a1 = va_arg (Arg, char *); while (* a1) {putchar (* a1); * a1 ++;} break; case 'D': // The parameter is an integer, int type a2 = va_arg (arg, int); putchar (a2 + '0'); break; default: // The parameter is other, output putchar (* str) according to the original form ); break ;}} va_end (arg);} int main () {char * str = "dc \ ts \ ndc \ ts! "; Int len = strlen (str); my_printf (str, len, 1, 'B'," zhangweina ", 2, 'I', 3,'t ', "welcome to you"); system ("pause"); return 0 ;}