要求:能完成下列函數的調用
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;
}
運行結果