Skip to content

Instantly share code, notes, and snippets.

@shihongzhi
Created November 18, 2010 08:21
Show Gist options
  • Save shihongzhi/704768 to your computer and use it in GitHub Desktop.
Save shihongzhi/704768 to your computer and use it in GitHub Desktop.
/*2010/11/18 shihongzhi
* 实现了printf,itoa,ftoa
* todo:%f的自定义小数点没有实现
*/
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
const double eps=1e-12;
void my_itoa(int val,char *buf)
{
const int radix=10;
char *p=buf; //start of the val char
int a;
char *b; //start of the digit char
char temp;
unsigned int u;
if(val<0){
*p++='-';
val=0-val;
}
b=p;
u=(unsigned int)val;
while(u>0){
a=u%radix;
u/=radix;
*p++=a+'0';
}
*p--='\0';
while(p>b){
temp=*p;
*p--=*b;
*b++=temp;
}
}
void my_ftoa(double val,char *buf,int digits)
{
const int radix=10;
char *p=buf;
char *b,*q;
char temp;
int a,cur_d,dec;
long long i_val=(long long)val;
double dec_val=val-i_val;
if(val<0){
*p++='-';
val=0-val;
}
b=p;
while(i_val>0){
a=i_val%radix;
i_val/=radix;
*p++=a+'0';
}
q=p-1;
while(q>b){
temp=*q;
*q--=*b;
*b++=temp;
}
if(fabs(dec_val-0.0)>eps)
{
*p++='.';
cur_d=0;
while(cur_d<digits){
cur_d++;
dec_val*=10;
dec=(int)dec_val;
dec_val-=dec;
*p++=dec+'0';
}
}
*p='\0';
}
void my_printf(const char *format,...)
{
va_list ap;
char c;
char ch;
char *p;
char ibuf[1000]; //刚开始写成了char *buf 出现了段错误,查了半个小时,悲剧
char dbuf[1000];
int i;
double d;
va_start(ap,format);
while(c=*format){
if(c=='%'){
// c=*(++format);
format++;
c=*format;
switch(c){
case 'c':
ch=va_arg(ap,int);
putchar(ch);
break;
case 's':
p=va_arg(ap,char*);
fputs(p,stdout);
break;
case 'd':
i=va_arg(ap,int);
my_itoa(i,ibuf);
fputs(ibuf,stdout);
break;
case 'f':
d=va_arg(ap,double);
my_ftoa(d,dbuf,6);
fputs(dbuf,stdout);
break;
default:
putchar('%');
putchar(c);
}
}
else{
putchar(c);
}
format++;
}
va_end(ap);
}
int main(void)
{
my_printf("int:%d,float:%f,char:%c,string:%s\n",12,13.1212611214,'a',"hello world");
my_printf("int:%d,float:%f,char:%c,string:%s\n",123456,1.1,'b',"hello123");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment