S1E29
#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 = '-';
putchar('-');
num = -num;
}
temp = num;
while (temp > 9)
{
dec *= 10;
temp /= 10;
}
while (dec != 0)
{
d = num / dec + '0';
putchar(num / dec + '0');
num = num % dec;
dec /= 10;
}
d = '\0';
return d;
}
void printStr(char *s)
{
int j;
for(j=0;s!='\0';j++)
{
putchar(s);
}
}
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!='\0')
{
if(str=='%')
{
if(str=='s')
{
s=va_arg(vap,char*);
printStr(s);
count+=strlen(s);
}
else if(str=='c')
{
c=va_arg(vap,int);
putchar(c);
count++;
}
else if(str=='d')
{
d=va_arg(vap,int);
myitoa(d,dd);
count+=strlen(dd);
}
i+=2;
}
else
{
putchar(str);
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 = {0} ;
va_list vap ;
va_start(vap , str) ;
strcpy(s , str) ;
for(i = 0 ; s ; i ++) {
if(s == '%' && s && (s == 'c' || s == 's' || s == 'd')) {
if(s == 'c' || s == 'd') {
d = va_arg(vap , int) ;
if(s == 'c') sprintf(s , "%c" , d) ;
else sprintf(s , "%d" , d) ;
} else if(s == 's') {
strcpy(s , va_arg(vap , const char *)) ;
}
i ++ ;
} else {
s = s ;
s = 0 ;
}
strcat(s , s) ;
}
va_end(vap) ;
printf("%s" , s) ;
return strlen(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) ;
}
页:
[1]