First, printf
function
The printf () function is a formatted output function that is generally used to output information in a prescribed format to a standard output device.
Prototype
int printf (const char* format, [argument] ...); Defined in Stdio.h
More printf detailed See links: printf () function detailed http://gaoxiaodiao.com/p/1.html
second, how to simulate the implementation of printf Analysis:
printf ("Hello haohaosong!\n");
printf ("%s", "Welcome to My bolg\n");
printf ("hell%c\n", ' O ');
We found that the parameters of the printf function are indeterminate
You must use something else to resolve the argument :
Using STDARG macros to solve variable parameter problems
Header file:<stdarg.h>
va_list;
Type Va_arg (va_list arg_ptr, type);
void Va_end (Va_list arg_ptr);
void Va_start (Va_list arg_ptr, Prev_param); (ANSI version)
under VC6.0, we go to the definition of the definition, which can be clearly found:
parsing:
Va_list is a macro-defined identifier that is a pointer to a character type
Va_start (ap,v) Remove the address of the variable that va_list defines, plus the number of variable elements
Va_arg (ap,t) takes the pointer to the content each time and moves the pointer back inside the macro
Va_end (AP) points The original pointer to null to prevent the occurrence of wild pointers three, specific code blocks:
#include <stdio.h>
#include <stdarg.h>
int my_printf (char* str,...)
{
va_list arg;//defines the char* variable arg
int count = 0;
char* str_tmp = NULL;
Va_start (ARG,STR),//For ARG initialization while
(*str!= ' ")
{
switch (*str) {case
' C ':
Putchar ( Va_arg (Arg,int));//Remove the character of a parameter and print the
count++;
break;
Case ' s ':
str_tmp = (char*) va_arg (arg,int);//Remove the address of a parameter, because this is the string while
(*str_tmp!= ' ")//Use the dereference for output
{
Putchar (*str_tmp);
count++;
str_tmp++;
}
break;
Default:
Putchar (*STR); Not for ' C ' or ' s ', then print it directly
count++;
break;
str++;
}
Va_end (ARG);//point arg to NULL to prevent wild pointer return
count;
}
int main ()
{
my_printf ("s CCC", "Hello", ' h ', ' h ', ' s ');
return 0;
}
Run Result: