#include <stdio.h>
#include <stdarg.h>
void get_string(char *buff, int value) {
if(value < 0) {
*buff++ = '-';
value = -value;
}
char temp[1024];
int i = 0;
do {
temp[i++] = (value % 10) + '0';
value /= 10;
} while(value);
for(int j = i - 1; j >= 0; --j) {
*buff++ = temp[j];
}
*buff = '\0';
}
int myprintf(const char *format, ...) {
int count = 0;
va_list arg;
va_start(arg, format);
while(*format) {
if(*format != '%') {
++count;
putchar(*format++);
continue;
}
++format;
const char *str;
char buff[1024];
switch(*format) {
case 'c':
putchar(va_arg(arg, int)); // no error
++count;
break;
case 's':
str = va_arg(arg, const char *);
output_string:
for(size_t i = 0; str[i]; ++i) {
putchar(str[i]);
++count;
}
break;
case 'd': {
int value = va_arg(arg, int);
get_string(buff, value);
str = buff;
goto output_string;
}
break;
default:
if(*format == '\0') goto end;
++count;
putchar(*format);
}
++format;
}
end:
va_end(arg);
return count;
}
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;
}
|