Before implementing the printf () function, we are dealing with an unusual problem, which is variable arguments. Since we know that printf can take many arguments besides a string. Therefore, we must use a standard library called stdarg.h to handle this problem with the variable argument. In this implementation context, we do not need to study the entire stdarg.h library because we use some macro functions from this library that are directly understood by our C program.
Here is a source of code that explains good and fast
#include<stdio.h>
#include<stdarg.h>
void Myprintf(char *,...);
char* convert(unsigned int, int);
int main()
{
Myprintf(" WWW.FIRMCODES.COM \n %d", 9);
return 0;
}
void Myprintf(char* format,...)
{
char *traverse;
unsigned int i;
char *s;
va_list arg;
va_start(arg, format);
for(traverse = format; *traverse != '\0'; traverse++)
{
while( *traverse != '%' )
{
putchar(*traverse);
traverse++;
}
traverse++;
switch(*traverse)
{
case 'c' : i = va_arg(arg,int);
putchar(i);
break;
case 'd' : i = va_arg(arg,int);
if(i<0)
{
i = -i;
putchar('-');
}
puts(convert(i,10));
break;
case 'o': i = va_arg(arg,unsigned int);
puts(convert(i,8));
break;
case 's': s = va_arg(arg,char *);
puts(s);
break;
case 'x': i = va_arg(arg,unsigned int);
puts(convert(i,16));
break;
}
}
va_end(arg);
}
char *convert(unsigned int num, int base)
{
static char Representation[]= "0123456789ABCDEF";
static char buffer[50];
char *ptr;
ptr = &buffer[49];
*ptr = '\0';
do
{
*--ptr = Representation[num%base];
num /= base;
}while(num != 0);
return(ptr);
}
source
share