天天看點

簡版printf函數實作

#include <stdio.h>
#include <stdarg.h>
#include <inttypes.h>

int reverse(int n, int *temp) {
   int digit = 0;
   do {
      *temp = *temp * 10 + n % 10;
      n /= 10;
      digit++;
   } while (n);
   return digit;
}

int output_num(int n, int digit) {
   int cnt = 0;
   while (digit--){
      putchar(n % 10 + '0');
      n /= 10;
      cnt++;
   }
   return cnt;
}
int my_printf(const char* frm, ...) {
   int cnt = 0;
   #define PUTC(a) putchar(a),cnt++
   va_list arg;
   va_start(arg, frm);
   for (int i = 0; frm[i]; i++) {
      switch (frm[i]) {
      case '%': {
         switch (frm[++i]) {
            case '%' :PUTC(frm[i]);break;
            case 'd' :{
               int temp = va_arg(arg, int);
               uint32_t x = 0;
               if (temp < 0) PUTC('-'), x = -temp;
               else x = temp;
               int x1 = x / 100000, x2 = x % 100000;
               int temp1 = 0, temp2 = 0;
               int digit1 = reverse(x1, &temp1);
               int digit2 = reverse(x2, &temp2);
               int digit3 = 0;
               if (x1) digit3 = 5 - digit2;
               else digit1 = 0;
               cnt += output_num(temp1, digit1);
               cnt += output_num(0, digit3);
               cnt += output_num(temp2, digit2);
            }break;
            case 's' :{
            const char *str = va_arg(arg, const char *);
            for (int i = 0; str[i]; i++) {
               PUTC(str[i]);
               }
            }break;
         }
      }break;
      default :PUTC(frm[i]);break;
      }
   }
    #undef PUTC
   va_end(arg);
   return cnt;
}

int main() {
   int a = 123;
   printf("int(a) = %d\n", 100);
   my_printf("int(a) = %d\n", 100);
   printf("hello world\n");
   my_printf("hello world\n");
   printf("int(a) = %d\n", -123);
   my_printf("int(a) = %d\n", -123);
   printf("int(a) = %d\n", INT32_MAX);
   my_printf("int(a) = %d\n", INT32_MAX);
   printf("int(a) = %d\n", INT32_MIN);
   my_printf("int(a) = %d\n", INT32_MIN);
   char *str = "I HAVE A PEN";
   printf("%s\n", str);
   my_printf("%s\n", str);
   printf("int (100500) = %d\n", 100500);
   my_printf("int (100500) = %d\n", 100500);
   int n;
   while (~scanf("%d", &n)) {
      printf("  has %d digits!\n", printf("%d", n));
      my_printf("  has %d digits!\n", my_printf("%d", n));
   }
  
   return 0;
}
           

繼續閱讀