马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
int myprintf(char*str,...);
char *myitoa(int num, char *d);
void printStr(char *s);
int main(void)
{
int i;
i = myprintf("Hello %s\n", "FishC");
myprintf("共打印了%d个字符(包含\\n)\n", i);
i = myprintf("int: %d, char: %c\n", -520, 'H');
myprintf("共打印了%d个字符(包含\\n)\n", i);
return 0;
}
char *myitoa(int num, char *d)
{
int dec = 1;
int i = 0;
int temp;
if (num < 0)
{
d[i++] = '-';
putchar('-');
num = -num;
}
temp = num;
while (temp > 9)
{
dec *= 10;
temp /= 10;
}
while (dec != 0)
{
d[i++] = num / dec + '0';
putchar(num / dec + '0');
num = num % dec;
dec /= 10;
}
d[i] = '\0';
return d;
}
void printStr(char *s)
{
int j;
for(j=0;s[j]!='\0';j++)
{
putchar(s[j]);
}
}
int myprintf(char*str,...)
{
int i=0,j,count=0;
int dec=1,temp;
char *s;
char *dd;
char c;
int d;
va_list vap;
va_start(vap,str);
while(str[i]!='\0')
{
if(str[i]=='%')
{
if(str[i++]=='s')
{
s=va_arg(vap,char*);
printStr(s);
count+=strlen(s);
}
else if(str[i++]=='c')
{
c=va_arg(vap,int);
putchar(c);
count++;
}
else if(str[i++]=='d')
{
d=va_arg(vap,int);
myitoa(d,dd);
count+=strlen(dd);
}
i+=2;
}
else
{
putchar(str[i]);
count++;
i++;
}
}
va_end(vap);
return count;
}
纠错
本帖最后由 jackz007 于 2021-8-21 23:20 编辑 #include <stdio.h>
#include <string.h>
#include <stdarg.h>
int myprintf(char const * str , ...)
{
int d , i ;
char s[3][256] = {0} ;
va_list vap ;
va_start(vap , str) ;
strcpy(s[0] , str) ;
for(i = 0 ; s[0][i] ; i ++) {
if(s[0][i] == '%' && s[0][i + 1] && (s[0][i + 1] == 'c' || s[0][i + 1] == 's' || s[0][i + 1] == 'd')) {
if(s[0][i + 1] == 'c' || s[0][i + 1] == 'd') {
d = va_arg(vap , int) ;
if(s[0][i + 1] == 'c') sprintf(s[2] , "%c" , d) ;
else sprintf(s[2] , "%d" , d) ;
} else if(s[0][i + 1] == 's') {
strcpy(s[2] , va_arg(vap , const char *)) ;
}
i ++ ;
} else {
s[2][0] = s[0][i] ;
s[2][1] = 0 ;
}
strcat(s[1] , s[2]) ;
}
va_end(vap) ;
printf("%s" , s[1]) ;
return strlen(s[1]) ;
}
int main(void)
{
int i ;
i = myprintf("Hello %s\n" , "FishC") ;
myprintf("共打印了%d个字符(包含\\n)\n", i) ;
i = myprintf("int: %d, char: %c\n", -520, 'H') ;
myprintf("共打印了%d个字符(包含\\n)\n", i) ;
}
|