Guest User

Untitled

a guest
Oct 9th, 2016
124
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdarg.h>
  2. #include <stdio.h> //for real printf and putchar
  3.  
  4. void myprintf(const char *, ...);
  5.  
  6. void _p_myprintf_int(int arg)
  7. {
  8.     printf("%d", arg); //we're just going to use real printf for simplicity
  9. }
  10.  
  11. void _p_myprintf_unsigned(unsigned arg)
  12. {
  13.     printf("%u", arg); //for simplicity
  14. }
  15.  
  16. void _p_myprintf_string(char *str)
  17. {
  18.     while (*str) //while current char is not null terminator
  19.         putchar(*str++); //put it to the screen, increment current
  20. }
  21.  
  22. void myprintf(const char *fmt, ...)
  23. {
  24.     va_list args; //this is actually just a placeholder to our first (variable) argument
  25.     va_start(args, fmt); //set up our list so we can retrieve it
  26.     while (*fmt) //loop through each character of the string
  27.     {
  28.         if (*fmt++ == '%') //our control character
  29.         {                              //we increment it as well so our next character is our type spec
  30.             switch (*fmt++) //case-select our list, and increment it as well.
  31.             {
  32.              case 'i': //integer
  33.                  _p_myprintf_int( va_arg(args, int) ); //type=int, delegate to our int func
  34.                  break;
  35.              case 'u': //unsigned int
  36.                  _p_myprintf_unsigned( va_arg(args, unsigned) ); //type=unsigned, delegate to unsigned func
  37.                  break;
  38.              case 's': //string
  39.                  _p_myprintf_string( va_arg(args, char*) ); //type=char-ptr, delegate to string func
  40.                  break;
  41.             }
  42.         }
  43.         else
  44.             putchar( *(fmt - 1) ); //print a regular char to screen. We have to subtract 1 because it was incremented already.
  45.     }
  46.     va_end(args);
  47. }
RAW Paste Data