The printf function implemented in this article is declared as:
void VarPrint(const char * format, ...);
It mainly realizes the printing of strings, characters and numbers (ps: positive and negative numbers and 0). Of course, this is only a part of the function. Subsequent versions will support printing in multiple formats, so stay tuned.
Analysis of Algorithms
Starting from the content to be printed, each time judge whether a character is '%', if it is not '%', then output as it is (putchar can be used), if it is '%', then judge the character after '%' It is s, or c, or d, and finally print the output according to the format.
Note: Remember not to use puts when printing strings, because puts will automatically wrap the line after printing the statement to be output.
Source code:
#define _CRT_SECURE_NO_WARNINGS 1 /* * Copyright (c) 2018, code farmer from sust * All rights reserved. * * File name: VarPrint.c * Function: simulate the implementation of the printf function * Support output in %s, %c, %d and other formats * * Current version: V1.0 * Author: sustzc * Completion date: April 20, 2018 11:12:26 */ # include <stdio.h> # include <assert.h> # include <stdarg.h> /* * Function name: PrintStr * * Function: print string * * Entry parameter: str * * Exit parameter: void * * Return type: void */ void PrintStr(char * str) { assert(NULL != str); while ('\0' != *str) { putchar(*str++); } return; } /* * Function name: PrintInt * * Function: print numbers * * Entry parameter: num * * Exit parameter: void * * Return type: void */ void PrintInt(int num) { if (num >= 0) { if (num > 9) { PrintInt(num / 10); } else { ; } putchar(num % 10 + '0'); } else { putchar('-'); if ((-num) > 9) { PrintInt((-num) / 10); } else { ; } putchar((-num)%10 + '0'); } return; } /* * Function name: VarPrint * * Function function: implement the printf function * * Entry parameters: format, ... * * Exit parameter: void * * Return type: void */ void VarPrint(const char * format, ...) { va_list arg; int i = 0; int count = 0; assert(NULL != format); va_start (arg, format); while ('\0' != *format) { if ('%' == *format) { switch(*(++format)) { case 's': PrintStr (va_arg (arg, char *)); break; case 'c': putchar (va_arg (arg, unsigned int)); break; case 'd': PrintInt (va_arg (arg, int)); break; default: break; } format++; } else { putchar(*format++); } } va_end (arg); return; } int main(void) { VarPrint("printstr: %s\n", "h e l l o"); VarPrint("printchar: %c\n", 'c'); VarPrint("printchar: %c\n", 'h'); VarPrint("printchar: %c\n", 'i'); VarPrint("printchar: %c\n", 'n'); VarPrint("printchar: %c\n", 'a'); VarPrint("printint: %d\n", -520); VarPrint("printint: %d\n", 1314); return 0; }
Output result: