下面是一个模拟库函数printf的程序,编译环境是vs2005。小可将在后面讨论它的实现原理。
#include "stdafx.h"
#include <conio.h>
#include <stdarg.h>
int Print ( char *str, ...);
int main()//主函数
{
Print("Integer:%d string:%s float:%f %t", 1, "this is test.", 20.2);
printf("\n%d%t", i);
_getche();
return 0;
}
int Print ( char *str, ...)
{
va_list ap;
char *p;
int argd;
char *args;
double argf;
int count;
va_start(ap, str);
p = str;
count = 0;
while(*p)
{
if(*p=='%')
{
p++;
switch(*p)
{
case 'd':
argd = va_arg(ap, int);
count += printf("%d", argd);
break;
case 's':
args = va_arg(ap, char *);
count += printf("%s", args);
break;
case 'f':
argf = va_arg(ap, double);
count += printf("%f", argf);
break;
default:
_putch(*p);
count++;
break;
}
}
else
{
_putch(*p);
count++;
}
p++;
}
va_end(ap);
return count;
}
#include "stdafx.h"
#include <conio.h>
#include <stdarg.h>
int Print ( char *str, ...);
int main()//主函数
{
Print("Integer:%d string:%s float:%f %t", 1, "this is test.", 20.2);
printf("\n%d%t", i);
_getche();
return 0;
}
int Print ( char *str, ...)
{
va_list ap;
char *p;
int argd;
char *args;
double argf;
int count;
va_start(ap, str);
p = str;
count = 0;
while(*p)
{
if(*p=='%')
{
p++;
switch(*p)
{
case 'd':
argd = va_arg(ap, int);
count += printf("%d", argd);
break;
case 's':
args = va_arg(ap, char *);
count += printf("%s", args);
break;
case 'f':
argf = va_arg(ap, double);
count += printf("%f", argf);
break;
default:
_putch(*p);
count++;
break;
}
}
else
{
_putch(*p);
count++;
}
p++;
}
va_end(ap);
return count;
}