要求:能完成下列函数的调用
print("sccc d.\n","hello",'b','i','t',100);
print函数原型:print(char*format, ...)
printf函数原型:
int printf( const char *format [, argument]... );
printf函数可以这样用:printf("%s","hello world");
printf("%s%c","hello worl",'d');
printf函数的模拟实现需用到函数可变参数
#include <stdio.h>
#include<stdlib.h>
#include<stdarg.h>
void pri(int num)
{
if (num > 9)
pri(num / 10);
printf("%d",num % 10);
}//递归打印数字
void print(char *format, ...)
{
va_list arg;
va_start(arg, format);//初始化arg指向未知参数列表的第一个参数
char *address = NULL;
int num = 0;
int i = 0;
while (*format != '\0')
{
char tmp = *format;
switch (tmp)
{
case 's':
address=(char *)va_arg(arg, int);
while (*address != '\0')
{
putchar(*address);
address++;
}
break;//打印字符串
case 'c':
putchar(va_arg(arg, char));
break;//打印字符
case 'd':
pri(va_arg(arg, int));
break;//打印数字
default:
putchar(*format);
break;
}
format++;
}
va_end(arg);
}
int main()
{
print("s ccc d.\n", "hello", 'b', 'i', 't',100);
system("pause");
return 0;
}
运行结果