C语言:模拟实现printf函数——my_printf函数哦

时间:2021-11-22 19:23:15

#define _CRT_SECURE_NO_WARNINGS 10
#include<stdio.h>
#include<stdarg.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>

//int printf( const char *format [, argument]... );
//模拟实现printf函数,可以实现my_printf(“s ccc”,“hello”,‘b’,‘i’,‘t’)

char *int_str(int nums)
{
    char str[32] = "0";
    int i = 0;
    for (i = 31; i >= 0; i--)
    {
        str[i] = (nums & 1) + '0';
        nums >>= 1;
    }
    printf("%s\n", str);
}

int my_printf(const char *format, ...)
{
    assert(format);
    va_list arg_list;
    va_start(arg_list, format);
    int count = 0;
    const char *start = format;
    while (*start != '\0')
    {
        if (*start == '%')
        {
            start++;
            switch (*start)
            {
            case 's':
            {
                char *ret = va_arg(arg_list, char *);
                fputs(ret, stdout);
                count = count + strlen(ret);
            }
                break;
            case 'c':
            {
                char _c = va_arg(arg_list, char);
                putchar(_c);
                count++;
            }
                break;
            case 'd':
            {
                int _d = va_arg(arg_list, int);
                char buf[10];
                _itoa(_d, buf,10);
                fputs(buf, stdout);
                count = count + strlen(buf);
            }
                break;

            case 'v':
            {
                int _dd = va_arg(arg_list, int);
                char *array = int_str(_dd);
                fputs(array, stdout);
                count = count + strlen(array);
            }
                break;
            }
            start++;
            continue;
        }
        putchar(*start);
        start++;
        count++;
    }
    va_end(arg_list);
    return count;
}

int main()
{
    my_printf("%s %c%c%c", "hello", 'b', 'i', 't');
    system("pause");
    return 0;
}