1. 程式人生 > >模擬實現printf函式,可變引數列表例項

模擬實現printf函式,可變引數列表例項

首先可通過CSDN檢視printf函式原型等資訊

實現功能:

Print formatted output to the standard output stream.

即格式化輸出並列印至標準輸出流。

函式原型:

int printf( const char *format [, argument]... );

返回值:

Each of these functions returns the number of characters printed, or a negative value if an error occurs.

即返回當前實際輸出的個數(整形)。

引數:

format    //格式

Format control    //格式控制

argument    //引數

Optional arguments   //可選引數

  由函式原型可知,可通過可變引數列表實現此函式,同時可看出有多少%就有多少引數,每個引數的型別由%後的字元決定。
  至此問題便簡單化了,只需分析以下兩點便可寫出函式:
  1.分析其中%的個數,分析其內容
  2.%後的格式控制與%緊密相連
具體程式碼如下:

#include <stdio.h>
#include <windows.h>
#include <stdarg.h>
#include <assert.h> void printd(int n)//把整形按字元型輸出 { if (n < 0) { putchar('-'); } if (n) { printd(n / 10); putchar(n % 10 + '0'); } } void my_printf(char* format, ...) { va_list arg; va_start(arg, format); while (*format) { if
(*format == '%') //判斷是否是% { format++; switch (*format) { case 's': //輸出字串 { char *ch = va_arg(arg, char*); while (*ch) { putchar(*ch++); } break; } case 'c':putchar(va_arg(arg, char)); //輸出字元 break; case 'd': printd(va_arg(arg, int)); //輸出整形 break; case '%':putchar('%'); //輸出% break; default: puts("format error!\n"); return; } format++; } else if (*format == '\\') { format++; if (*format == 'n') { puts("\n"); //輸出\n } } else { putchar(*format); format++; } } va_end(arg); } int main() { my_printf("%s %c%c%c %d\n", "hello", 'b', 'i', 't', 100); system("pause"); return 0; }