利用可變參數模擬實現簡易printf

printf一般是這麼使用的, printf (“Characters: %c %c \n”, ‘a’, 65);
它是可變參數,遇到%s,%c,%d就格式化輸出
因爲我們重點是瞭解學習可變參數,因此,我們簡化一下,遇到c,s,d就格式化輸出
當然也許你會說那麼想輸出c字符咋辦?其實不難,只要掃描的時候向printf學習用%c輸出,c直接輸出,只不過我們重點不在這個掃描字符串分析,而是瞭解學習可變參數~

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

void MyPrintf(const char* format, ...)
{
    assert(format != NULL);

    va_list args;

    va_start(args, format);

    while (*format != '\0')
    {
        char ch = *format;
        switch (ch)
        {
        case 'c':
            {
                    char tmp = va_arg(args, char);
                    putc(tmp, stdout);
                    break;
            }
        case 's':
            {
                    char* s = va_arg(args, char*);
                    while (*s != '\0')
                    {
                        putc(*s++, stdout);
                    }
                    break;
            }
        default:
            {
                   putc(ch, stdout);
                   break;
            }
        }

        format++;
    }

    va_end(args);
}


int main()
{
    MyPrintf("hello i am cc, s", 'x', 'y', "ni hao\n");

    return 0;
}
發佈了96 篇原創文章 · 獲贊 119 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章