首先可通过优快云查看printf函数原型等信息
实现功能:
Print formatted output to the standard output stream.
即格式化输出并打印至标准输出流。
函数原型:
int printf( const char *format [, argument]... );
返回值:
Each of these functions returns the number of characters printed, or a negative value if an error occurs.
即返回当前实际输出的个数(整形)。
参数:
format //格式
Format control //格式控制
argument //参数
Optional arguments //可选参数
由函数原型可知,可通过可变参数列表实现此函数,同时可看出有多少%就有多少参数,每个参数的类型由%后的字符决定。
至此问题便简单化了,只需分析以下两点便可写出函数:
1.分析其中%的个数,分析其内容
2.%后的格式控制与%紧密相连
具体代码如下:
#include <stdio.h>
#include <windows.h>
#include <stdarg.h>
#include <assert.h>
void printd(int n)//把整形按字符型输出
{
if (n < 0)
{
putchar('-');
}
if (n)
{
printd(n / 10);
putchar(n % 10 + '0');
}
}
void my_printf(char* format, ...)
{
va_list arg;
va_start(arg, format);
while (*format)
{
if (*format == '%') //判断是否是%
{
format++;
switch (*format)
{
case 's': //输出字符串
{
char *ch = va_arg(arg, char*);
while (*ch)
{
putchar(*ch++);
}
break;
}
case 'c':putchar(va_arg(arg, char)); //输出字符
break;
case 'd': printd(va_arg(arg, int)); //输出整形
break;
case '%':putchar('%'); //输出%
break;
default: puts("format error!\n");
return;
}
format++;
}
else if (*format == '\\')
{
format++;
if (*format == 'n')
{
puts("\n"); //输出\n
}
}
else
{
putchar(*format);
format++;
}
}
va_end(arg);
}
int main()
{
my_printf("%s %c%c%c %d\n", "hello", 'b', 'i', 't', 100);
system("pause");
return 0;
}