Given this code, I was to finish it by creating the printint(), printstring(), and printhex() functions.
Before you start this please go thorough this function va_arg() to make the code undersatandable
extern int printchar(int);
void myprintf(const char *fmt, ...);
{
const char *p;
va_list argp;
int i;
char *s;
char fmtbuf[256];
va_start(argp, fmt);
for(p + fmt; *p != '\0'; p++)
{
if(*p != '%')
{
putchar(*p);
continue;
}
switch(*++p)
{
case 'c':
i = va_arg(argp, int);
putchar(i);
break;
case 'd':
i = va_arg(argp, int);
printint(i);
break;
case 's':
s = va_arg(argp, char *);
printstring(s);
break;
case 'x':
i = va_arg(argp, int);
printhex(i);
break;
case '%':
putchar('%');
break;
}
}
va_end(argp);
}
void printint(int i)
{
int digit;
digit = i % 10;
digit = digit + '0';
i = i / 10;
putchar(i);
}
void printstring(char s)
{
putchar(s);
}
void printhex(int i)
{
for (int a=2*sizeof(int) - 1; a>=0; a--) {
putchar("0123456789ABCDEF"[((i >> a*4) & 0xF)]);
}
}
putchar("0123456789ABCDEF"[((i >> a*4) & 0xF)]);
}
}
1 comment:
include this before you test it
#include stdarg.h
Post a Comment