繁体   English   中英

我正在尝试创建自己的 printf 函数,但我不知道如何包含格式说明符

[英]I am trying to create my own printf function, but I dont know how to include the format specifiers

我正在尝试创建自己的printf函数,这是我的代码:

#include <unistd.h>
#include <stdarg.h>

int write_char(char c);
int myPrintf(const char *format, ...);
int string_length(const char *string, int x);

int main(void)
{
    myPrintf("Let's try to printf a simple sentence.\n");
    myPrintf("Hello%d\n", 1);

    return (0);
}

int myPrintf(const char *format, ...)
{
    int i = 0, length = 0, j;

    length = string_length(format, j);

    va_list args;
    va_start(args, format);

    while (i < length)
    {
        if (format[i] != '%')
        {
           write_char(format[i]);
        } else
        {
            i++;
            switch(format[i])
            {
                case 'd':
                {
                    int x = va_arg(args, int);
                    write_char(x + '0');
                }
            }
        }
        i++;
    }
}

int string_length(const char *string, int x)
{
    if (*string != '\0')
    {
        return (string_length(string + 1, x + 1));
    }
        return (x); 
}

int write_char(char c)
{
    return(write(1, &c, 1));
}

但是当我尝试运行我的代码时,我得到以下输出:

Let's try to printf a simple sentence.
Hello
����|$����4����d���dM���������V�������4zRx
                                         ����&D$4`���@FJ
s                                                       �?:*3$"\x���tp���0�q���<E�C
������E�C
t:���=E�C
aW���*E�C
�@@
������o���
�
 �?Hx� ������ox���o���o`���o�=0@PLet's try to printf a simple sentence.
Hello
����|$����4����d���dM���������V�������4zRx
                                         ����&D$4`���@FJ
s                                                       �?:*3$"\x���tp���0�q���<E�C
������E�C
t:���=E�C
aW���*E�C
�A�7V@A�7V@
������o�3�7V�4�7V�3�7V
�
 QD���o�7VHx6�7V�5�7�  ������ox���o���o`5�7V���o�= 
.�� '0��p�"���]���!�p�7VSegmentation fault (core dumped)

它确实打印了字符串,但当我包含格式说明符以打印整数时则不打印:

myPrintf("Hello%d\n", 1);

为什么会这样?

我已经解决了这个问题,代码如下:

int myPrintf(const char *format, ...)
{
    int i = 0, length = 0, j = 0;

    length = string_length(format, j);

    va_list args;
    va_start(args, format);

    while (i < length)
    {
        if (format[i] != '%')
        {
           write_char(format[i]);
        } else
        {
            i++;
            switch(format[i])
            {
                case 'd':
                {
                    int x = va_arg(args, int);
                    write_char(x + '0');
                }
            }
        }
        i++;
    }
    va_end(args);
    return (0);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM