最近看《C和指针》,里面讲到了可变参数如下图,所以就想自己实现一个myprintf
下面是实现的简单的myprintf.h
#include
#define NULL 0
va_list args;
char sign[] = { '0','1','2','3','4','5',
'6','7','8','9','a','b',
'c','d','e','f'};
void print_int( int num, int mode, int flag )
{
if( num == 0 )
{
if( flag == 0 )
{
putchar( '0' );
return;
}
else
{
return;
}
}
print_int( num/mode, mode, 1 );
putchar( sign[ num%mode ] );
}
void print_str( char const *str )
{
if( str == NULL )
{
return;
}
while( *str != '\0' )
{
putchar( *str );
str++;
}
}
void print_float( float num )
{
int part = num/1;
print_int( part, 10, 0 );
putchar( '.' );
part=num*1000000-part*1000000;
print_int( part, 10, 0 );
}
void check_type( char type )
{
switch( type )
{
case 'd':
{
int num = va_arg( args, int );
if( num < 0 )
{
putchar('-');
num = num * (-1);
}
print_int( num, 10, 0 );
break;
}
case 'c':
{
char ch = (char)va_arg( args, int );
putchar( ch );
break;
}
case 's':
{
char *str = va_arg( args, char * );
print_str( str );
break;
}
case 'f':
{
float num = (float)va_arg( args, double );
if( num < 0 )
{
putchar('-');
num = num * (-1);
}
print_float( num );
break;
}
case 'p':
{
int num = va_arg( args, int );
putchar( '0' );
putchar( 'x' );
print_int( num, 16, 0 );
break;
}
default:
{
putchar( '%' );
putchar( type );
}
}
}
void myprintf( const char *format, ... )
{
if( format == NULL )
{
return;
}
va_start( args, format );
while( *format != '\0' )
{
while( *format != '%' && *format != '\0' )
{
putchar( *format );
format++;
}
if( *format != '\0' )
{
format++;
if( *format != '\0' )
{
check_type( *format );
format++;
}
else
{
putchar( *(format-1) );
}
}
}
va_end( args );
}
把myprintf定义成用来调试代码的函数
debug.h
#include "myprintf.h"
#ifndef __DEBUG__
#define debug_msg(fmt, args...)
#else
#define debug_msg(fmt, args...) myprintf(fmt, ##args)
#endif
下面写个例子简单测试下
myprintf_test.c
#include "debug.h"
int main()
{
int num = -5;
char ch = 'a';
char *str = "abcdef";
char *ptr = NULL;
float min = 0.1415926;
printf("printf效果:\n\n");
printf("num=%d,\\ch=%c,str=%s,\nmin=%f,str_addr=%p,ptr_addr=%p \
\n",num,ch,str,min,str,ptr);
myprintf("\nmyprintf的效果:\n\n");
debug_msg("%%%num=%d,\\ch=%c,str=%s,\nmin=%f,str_addr=%p,ptr_addr=%p \
\n%",num,ch,str,min,str,ptr);
myprintf("\n");
return 0;
}
运行一下
不知道为什么自带的printf不支持多个%%%的输出,转义也不行