c语言自建一个窗口,C语言 手把手教你写个自定义printf

一个简单的例子

__printf (const char *format, ...)

{

va_list arg;

int done;

va_start (arg, format);

done = vfprintf (stdout, format, arg);

va_end (arg);

return done;

}

Module 1: Initializing Myprintf’s arguments

va_list arg;

In this section, we initialize the arguments of Myprintf( ) function by using standard argument library.

va_start(arg, format);

This line declares a variable, arg, which we use to manipulating the argument list containing variable arguments of Myprintf( ). The data type of the variable is va_list, a special type defined by .

Module 2: Fetching and executing arguments

i = va_arg(arg,int);

va_arg() fetches the next argument from the argument list. The second parameter to va_arg() is the data type of the argument we expect.

Note: va_arg( ) function will never receive arguments of type char, short int, or float. va_arg( ) function only accept arguments of type char *, unsigned int, int or double.

Module 3: Closing argument list to necessary clean-up

va_end(arg); Finally, when we’re finished processing the all arguments, we call va_end(), which performs any necessary cleanup.

一个复杂的例子

#include

#include

void Myprintf(char *,...); //Our printf function

char* convert(unsigned int, int); //Convert integer number into octal, hex, etc.

int main()

{

Myprintf(" WWW.FIRMCODES.COM \n %d", 9);

return 0;

}

void Myprintf(char* format,...)

{

char *traverse;

unsigned int i;

char *s;

//Module 1: Initializing Myprintf's arguments

va_list arg;

va_start(arg, format);

for(traverse = format; *traverse != '\0'; traverse++)

{

while( *traverse != '%' )

{

putchar(*traverse);

traverse++;

}

traverse++;

//Module 2: Fetching and executing arguments

switch(*traverse)

{

case 'c' : i = va_arg(arg,int); //Fetch char argument

putchar(i);

break;

case 'd' : i = va_arg(arg,int); //Fetch Decimal/Integer argument

if(i<0)

{

i = -i;

putchar('-');

}

puts(convert(i,10));

break;

case 'o': i = va_arg(arg,unsigned int); //Fetch Octal representation

puts(convert(i,8));

break;

case 's': s = va_arg(arg,char *); //Fetch string

puts(s);

break;

case 'x': i = va_arg(arg,unsigned int); //Fetch Hexadecimal representation

puts(convert(i,16));

break;

}

}

//Module 3: Closing argument list to necessary clean-up

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值