#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#define M 100
extern int My_Printf(const char * flag,...);
extern int My_Printf(const char * flag,...)
{
assert(flag);
char *buf = (char *)malloc(M);
if (buf == NULL)
{
perror("malloc");
return -1;
}
memset(buf,0,M);
strcpy(buf,flag);
va_list data_list;
va_start(data_list,flag);
char *p = NULL;
while(1)
{
p = strchr(buf,'%');//char *strchr( const char *str, int ch );
if(p == NULL)
{
printf("%s",buf);
return 0;
}
else
{
*p = '\0';
printf("%s",buf);
}
if(*(p+1) == 'd')
{
printf("%d",va_arg(data_list,int));
}
else if(*(p+1) == 'c')
{
char c;
c = (char)va_arg(data_list,int);
printf("%c",c);
}
else
{
printf("%c",*p);
}
*(p+1)= '\0';
buf = p+2;
}
return 0;
}
int main()
{
char a= 'S';
My_Printf("hello world%c---%c---%d\n",a,a,a);
return 0;
}
心血来潮,写了一个简单模拟printf函数的方法~~~
最新推荐文章于 2024-09-09 19:25:15 发布