《C和指针》第7章编程练习第5题

题目如下:

实现一个简化printf函数,它能够处理%d、%f、%s和%c格式码。根据ANSI标准的原则,其他格式码的行为是未定义的。你可以假定已经存在函数print_integer和print_float,用于打印这些类型的值。对于另外两种类型的值,使用putchar来打印。

下面是我的代码实现(print_integer和print_float这两个我没有实现,直接调用的printf函数模拟的):

#include <stdio.h>
#include <stdarg.h>


int my_printf (char *format, ...);
void print_integer(int i);
void print_float(float f);


int
main (void)
{
int i = 50, count;
float f = 3.14;
char *str = "lilipo";
char ch = 'c';
count = my_printf("ch=%c, str=%s, f=%lf, f=%f%, i=%d%\n", ch, str, f, i);
printf("count=%d\n", count);
return 0;
}


int
my_printf (char *format, ...)
{
char ch, *strp;
int count = 0, tempch;
va_list var_arg;
va_start(var_arg, format);
while ((ch = *format++) != '\0') {
if (ch == '%') {
if ((ch = *format++) != '\0') {
if (ch == 'd') { 
count++;
print_integer(va_arg(var_arg, int));
continue;
} else if (ch == 'f') {
count++;
print_float(va_arg(var_arg, double));
continue;
} else if (ch == 'c') {
count++;
tempch = va_arg(var_arg, int);
putchar(tempch);
continue;
} else if (ch == 's') {
count++;
strp = va_arg(var_arg, char *);
while (*strp != '\0')
putchar(*strp++);
continue;
                } else {
putchar('%');
putchar(ch);
}
} else
putchar('%');
} else {
putchar(ch);
}
}
va_end(var_arg);
return count;
}


void 
print_integer(int i)
{
printf("%d", i);
}


void 
print_float(float f)
{
printf("%f", f);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值