stdarg.c 980 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <stdarg.h>
  2. struct node { int a[4]; } x = {1,2,3,4};
  3. print(char *fmt, ...);
  4. main() {
  5. print("test 1\n");
  6. print("test %s\n", "2");
  7. print("test %d%c", 3, '\n');
  8. print("%s%s %w%c", "te", "st", 4, '\n');
  9. print("%s%s %f%c", "te", "st", 5.0, '\n');
  10. print("%b %b %b %b %b %b\n", x, x, x, x, x, x);
  11. return 0;
  12. }
  13. print(char *fmt, ...) {
  14. va_list ap;
  15. va_start(ap, fmt);
  16. for (; *fmt; fmt++)
  17. if (*fmt == '%')
  18. switch (*++fmt) {
  19. case 'b': {
  20. struct node x = va_arg(ap, struct node);
  21. printf("{%d %d %d %d}", x.a[0], x.a[1], x.a[2], x.a[3]);
  22. break;
  23. }
  24. case 'c':
  25. printf("%c", va_arg(ap, char));
  26. break;
  27. case 'd':
  28. printf("%d", va_arg(ap, int));
  29. break;
  30. case 'w':
  31. printf("%x", va_arg(ap, short));
  32. break;
  33. case 's':
  34. printf("%s", va_arg(ap, char *));
  35. break;
  36. case 'f':
  37. printf("%f", va_arg(ap, double));
  38. break;
  39. default:
  40. printf("%c", *fmt);
  41. break;
  42. }
  43. else
  44. printf("%c", *fmt);
  45. va_end(ap);
  46. }